From 8c2cd60aeac1ff005313dd180d91d2f8daac76c6 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Sat, 15 Mar 2025 02:55:44 +0000 Subject: [PATCH 1/2] docs: update composer supported environments version match PiperOrigin-RevId: 737034878 Source-Link: https://github.com/googleapis/googleapis/commit/d5b0985766af88699d7b112d64f338cfd8403023 Source-Link: https://github.com/googleapis/googleapis-gen/commit/566bff27465eff2f6a116bce89f7ae765b5127c0 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLW9yY2hlc3RyYXRpb24tYWlyZmxvdy8uT3dsQm90LnlhbWwiLCJoIjoiNTY2YmZmMjc0NjVlZmYyZjZhMTE2YmNlODlmN2FlNzY1YjUxMjdjMCJ9 --- .../v1/.coveragerc | 13 + .../v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 143 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/conf.py | 376 + .../v1/docs/index.rst | 7 + .../v1/docs/service_v1/environments.rst | 10 + .../v1/docs/service_v1/image_versions.rst | 10 + .../v1/docs/service_v1/services_.rst | 7 + .../v1/docs/service_v1/types_.rst | 6 + .../orchestration/airflow/service/__init__.py | 159 + .../airflow/service/gapic_version.py | 16 + .../orchestration/airflow/service/py.typed | 2 + .../airflow/service_v1/__init__.py | 160 + .../airflow/service_v1/gapic_metadata.json | 422 + .../airflow/service_v1/gapic_version.py | 16 + .../orchestration/airflow/service_v1/py.typed | 2 + .../airflow/service_v1/services/__init__.py | 15 + .../services/environments/__init__.py | 22 + .../services/environments/async_client.py | 3216 +++ .../services/environments/client.py | 3589 ++++ .../services/environments/pagers.py | 583 + .../environments/transports/README.rst | 9 + .../environments/transports/__init__.py | 38 + .../services/environments/transports/base.py | 526 + .../services/environments/transports/grpc.py | 1070 + .../environments/transports/grpc_asyncio.py | 1220 ++ .../services/environments/transports/rest.py | 4687 ++++ .../environments/transports/rest_base.py | 1082 + .../services/image_versions/__init__.py | 22 + .../services/image_versions/async_client.py | 536 + .../services/image_versions/client.py | 897 + .../services/image_versions/pagers.py | 166 + .../image_versions/transports/README.rst | 9 + .../image_versions/transports/__init__.py | 38 + .../image_versions/transports/base.py | 197 + .../image_versions/transports/grpc.py | 402 + .../image_versions/transports/grpc_asyncio.py | 437 + .../image_versions/transports/rest.py | 742 + .../image_versions/transports/rest_base.py | 196 + .../airflow/service_v1/types/__init__.py | 152 + .../airflow/service_v1/types/environments.py | 3089 +++ .../service_v1/types/image_versions.py | 148 + .../airflow/service_v1/types/operations.py | 147 + .../v1/mypy.ini | 3 + .../v1/noxfile.py | 280 + ...erated_environments_check_upgrade_async.py | 56 + ...nerated_environments_check_upgrade_sync.py | 56 + ...d_environments_create_environment_async.py | 55 + ...ed_environments_create_environment_sync.py | 55 + ..._create_user_workloads_config_map_async.py | 52 + ...s_create_user_workloads_config_map_sync.py | 52 + ...ents_create_user_workloads_secret_async.py | 52 + ...ments_create_user_workloads_secret_sync.py | 52 + ...ed_environments_database_failover_async.py | 55 + ...ted_environments_database_failover_sync.py | 55 + ...d_environments_delete_environment_async.py | 55 + ...ed_environments_delete_environment_sync.py | 55 + ..._delete_user_workloads_config_map_async.py | 50 + ...s_delete_user_workloads_config_map_sync.py | 50 + ...ents_delete_user_workloads_secret_async.py | 50 + ...ments_delete_user_workloads_secret_sync.py | 50 + ...ironments_execute_airflow_command_async.py | 51 + ...vironments_execute_airflow_command_sync.py | 51 + ...onments_fetch_database_properties_async.py | 52 + ...ronments_fetch_database_properties_sync.py | 52 + ...ated_environments_get_environment_async.py | 51 + ...rated_environments_get_environment_sync.py | 51 + ...nts_get_user_workloads_config_map_async.py | 52 + ...ents_get_user_workloads_config_map_sync.py | 52 + ...onments_get_user_workloads_secret_async.py | 52 + ...ronments_get_user_workloads_secret_sync.py | 52 + ...ed_environments_list_environments_async.py | 52 + ...ted_environments_list_environments_sync.py | 52 + ...s_list_user_workloads_config_maps_async.py | 53 + ...ts_list_user_workloads_config_maps_sync.py | 53 + ...ments_list_user_workloads_secrets_async.py | 53 + ...nments_list_user_workloads_secrets_sync.py | 53 + ...rated_environments_list_workloads_async.py | 53 + ...erated_environments_list_workloads_sync.py | 53 + ...erated_environments_load_snapshot_async.py | 55 + ...nerated_environments_load_snapshot_sync.py | 55 + ...environments_poll_airflow_command_async.py | 51 + ..._environments_poll_airflow_command_sync.py | 51 + ...erated_environments_save_snapshot_async.py | 55 + ...nerated_environments_save_snapshot_sync.py | 55 + ...environments_stop_airflow_command_async.py | 51 + ..._environments_stop_airflow_command_sync.py | 51 + ...d_environments_update_environment_async.py | 55 + ...ed_environments_update_environment_sync.py | 55 + ..._update_user_workloads_config_map_async.py | 51 + ...s_update_user_workloads_config_map_sync.py | 51 + ...ents_update_user_workloads_secret_async.py | 51 + ...ments_update_user_workloads_secret_sync.py | 51 + ...mage_versions_list_image_versions_async.py | 52 + ...image_versions_list_image_versions_sync.py | 52 + ...loud.orchestration.airflow.service.v1.json | 4004 ++++ .../v1/scripts/fixup_service_v1_keywords.py | 200 + .../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 + .../tests/unit/gapic/service_v1/__init__.py | 16 + .../gapic/service_v1/test_environments.py | 17371 +++++++++++++++ .../gapic/service_v1/test_image_versions.py | 2847 +++ .../v1beta1/.coveragerc | 13 + .../v1beta1/.flake8 | 33 + .../v1beta1/MANIFEST.in | 2 + .../v1beta1/README.rst | 143 + .../v1beta1/airflow-service-v1beta1-py.tar.gz | 0 .../v1beta1/docs/_static/custom.css | 3 + .../v1beta1/docs/conf.py | 376 + .../v1beta1/docs/index.rst | 7 + .../docs/service_v1beta1/environments.rst | 10 + .../docs/service_v1beta1/image_versions.rst | 10 + .../docs/service_v1beta1/services_.rst | 7 + .../v1beta1/docs/service_v1beta1/types_.rst | 6 + .../orchestration/airflow/service/__init__.py | 161 + .../airflow/service/gapic_version.py | 16 + .../orchestration/airflow/service/py.typed | 2 + .../airflow/service_v1beta1/__init__.py | 162 + .../service_v1beta1/gapic_metadata.json | 437 + .../airflow/service_v1beta1/gapic_version.py | 16 + .../airflow/service_v1beta1/py.typed | 2 + .../service_v1beta1/services/__init__.py | 15 + .../services/environments/__init__.py | 22 + .../services/environments/async_client.py | 3350 +++ .../services/environments/client.py | 3723 ++++ .../services/environments/pagers.py | 583 + .../environments/transports/README.rst | 9 + .../environments/transports/__init__.py | 38 + .../services/environments/transports/base.py | 540 + .../services/environments/transports/grpc.py | 1096 + .../environments/transports/grpc_asyncio.py | 1251 ++ .../services/environments/transports/rest.py | 4862 +++++ .../environments/transports/rest_base.py | 1121 + .../services/image_versions/__init__.py | 22 + .../services/image_versions/async_client.py | 536 + .../services/image_versions/client.py | 897 + .../services/image_versions/pagers.py | 166 + .../image_versions/transports/README.rst | 9 + .../image_versions/transports/__init__.py | 38 + .../image_versions/transports/base.py | 197 + .../image_versions/transports/grpc.py | 402 + .../image_versions/transports/grpc_asyncio.py | 437 + .../image_versions/transports/rest.py | 742 + .../image_versions/transports/rest_base.py | 196 + .../airflow/service_v1beta1/types/__init__.py | 154 + .../service_v1beta1/types/environments.py | 3162 +++ .../service_v1beta1/types/image_versions.py | 148 + .../service_v1beta1/types/operations.py | 143 + .../v1beta1/mypy.ini | 3 + .../v1beta1/noxfile.py | 280 + ...erated_environments_check_upgrade_async.py | 55 + ...nerated_environments_check_upgrade_sync.py | 55 + ...d_environments_create_environment_async.py | 55 + ...ed_environments_create_environment_sync.py | 55 + ..._create_user_workloads_config_map_async.py | 52 + ...s_create_user_workloads_config_map_sync.py | 52 + ...ents_create_user_workloads_secret_async.py | 52 + ...ments_create_user_workloads_secret_sync.py | 52 + ...ed_environments_database_failover_async.py | 55 + ...ted_environments_database_failover_sync.py | 55 + ...d_environments_delete_environment_async.py | 55 + ...ed_environments_delete_environment_sync.py | 55 + ..._delete_user_workloads_config_map_async.py | 50 + ...s_delete_user_workloads_config_map_sync.py | 50 + ...ents_delete_user_workloads_secret_async.py | 50 + ...ments_delete_user_workloads_secret_sync.py | 50 + ...ironments_execute_airflow_command_async.py | 51 + ...vironments_execute_airflow_command_sync.py | 51 + ...onments_fetch_database_properties_async.py | 52 + ...ronments_fetch_database_properties_sync.py | 52 + ...ated_environments_get_environment_async.py | 51 + ...rated_environments_get_environment_sync.py | 51 + ...nts_get_user_workloads_config_map_async.py | 52 + ...ents_get_user_workloads_config_map_sync.py | 52 + ...onments_get_user_workloads_secret_async.py | 52 + ...ronments_get_user_workloads_secret_sync.py | 52 + ...ed_environments_list_environments_async.py | 52 + ...ted_environments_list_environments_sync.py | 52 + ...s_list_user_workloads_config_maps_async.py | 53 + ...ts_list_user_workloads_config_maps_sync.py | 53 + ...ments_list_user_workloads_secrets_async.py | 53 + ...nments_list_user_workloads_secrets_sync.py | 53 + ...rated_environments_list_workloads_async.py | 53 + ...erated_environments_list_workloads_sync.py | 53 + ...erated_environments_load_snapshot_async.py | 55 + ...nerated_environments_load_snapshot_sync.py | 55 + ...environments_poll_airflow_command_async.py | 51 + ..._environments_poll_airflow_command_sync.py | 51 + ...d_environments_restart_web_server_async.py | 55 + ...ed_environments_restart_web_server_sync.py | 55 + ...erated_environments_save_snapshot_async.py | 55 + ...nerated_environments_save_snapshot_sync.py | 55 + ...environments_stop_airflow_command_async.py | 51 + ..._environments_stop_airflow_command_sync.py | 51 + ...d_environments_update_environment_async.py | 55 + ...ed_environments_update_environment_sync.py | 55 + ..._update_user_workloads_config_map_async.py | 51 + ...s_update_user_workloads_config_map_sync.py | 51 + ...ents_update_user_workloads_secret_async.py | 51 + ...ments_update_user_workloads_secret_sync.py | 51 + ...mage_versions_list_image_versions_async.py | 52 + ...image_versions_list_image_versions_sync.py | 52 + ...orchestration.airflow.service.v1beta1.json | 4157 ++++ .../scripts/fixup_service_v1beta1_keywords.py | 201 + .../v1beta1/setup.py | 98 + .../v1beta1/testing/constraints-3.10.txt | 6 + .../v1beta1/testing/constraints-3.11.txt | 6 + .../v1beta1/testing/constraints-3.12.txt | 6 + .../v1beta1/testing/constraints-3.13.txt | 6 + .../v1beta1/testing/constraints-3.7.txt | 10 + .../v1beta1/testing/constraints-3.8.txt | 6 + .../v1beta1/testing/constraints-3.9.txt | 6 + .../v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/service_v1beta1/__init__.py | 16 + .../service_v1beta1/test_environments.py | 17816 ++++++++++++++++ .../service_v1beta1/test_image_versions.py | 2847 +++ 229 files changed, 105680 insertions(+) create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/environments.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/image_versions.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/py.typed create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/async_client.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/pagers.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/base.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/image_versions.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/operations.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.flake8 create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/README.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/airflow-service-v1beta1-py.tar.gz create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/environments.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/image_versions.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/services_.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/types_.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/py.typed create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/py.typed create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/async_client.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/pagers.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/base.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/image_versions.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_async.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_sync.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/setup.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py create mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/.coveragerc b/owl-bot-staging/google-cloud-orchestration-airflow/v1/.coveragerc new file mode 100644 index 000000000000..7b27e381927a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/orchestration/airflow/service/__init__.py + google/cloud/orchestration/airflow/service/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-orchestration-airflow/v1/.flake8 b/owl-bot-staging/google-cloud-orchestration-airflow/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/MANIFEST.in b/owl-bot-staging/google-cloud-orchestration-airflow/v1/MANIFEST.in new file mode 100644 index 000000000000..0dfd92c7eac7 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/orchestration/airflow/service *.py +recursive-include google/cloud/orchestration/airflow/service_v1 *.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/README.rst new file mode 100644 index 000000000000..4f24fd5ece7c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Cloud Orchestration Airflow Service 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 Orchestration Airflow Service 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 + + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + + +Examples +^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + + +Examples +^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py new file mode 100644 index 000000000000..0d6b253deba3 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow 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-orchestration-airflow" +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 Orchestration Airflow 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-orchestration-airflow-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-orchestration-airflow.tex", + u"google-cloud-orchestration-airflow 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-orchestration-airflow", + u"Google Cloud Orchestration Airflow Service 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-orchestration-airflow", + u"google-cloud-orchestration-airflow Documentation", + author, + "google-cloud-orchestration-airflow", + "GAPIC library for Google Cloud Orchestration Airflow Service 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-orchestration-airflow/v1/docs/index.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/index.rst new file mode 100644 index 000000000000..728aa8ab3564 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + service_v1/services_ + service_v1/types_ diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/environments.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/environments.rst new file mode 100644 index 000000000000..b871d8d059ce --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/environments.rst @@ -0,0 +1,10 @@ +Environments +------------------------------ + +.. automodule:: google.cloud.orchestration.airflow.service_v1.services.environments + :members: + :inherited-members: + +.. automodule:: google.cloud.orchestration.airflow.service_v1.services.environments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/image_versions.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/image_versions.rst new file mode 100644 index 000000000000..8b2bcb1a902a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/image_versions.rst @@ -0,0 +1,10 @@ +ImageVersions +------------------------------- + +.. automodule:: google.cloud.orchestration.airflow.service_v1.services.image_versions + :members: + :inherited-members: + +.. automodule:: google.cloud.orchestration.airflow.service_v1.services.image_versions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/services_.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/services_.rst new file mode 100644 index 000000000000..0957e0c567a5 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/services_.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Orchestration Airflow Service v1 API +============================================================== +.. toctree:: + :maxdepth: 2 + + environments + image_versions diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/types_.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/types_.rst new file mode 100644 index 000000000000..b49b771a92a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Orchestration Airflow Service v1 API +=========================================================== + +.. automodule:: google.cloud.orchestration.airflow.service_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py new file mode 100644 index 000000000000..a031606b9262 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py @@ -0,0 +1,159 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.orchestration.airflow.service_v1.services.environments.client import EnvironmentsClient +from google.cloud.orchestration.airflow.service_v1.services.environments.async_client import EnvironmentsAsyncClient +from google.cloud.orchestration.airflow.service_v1.services.image_versions.client import ImageVersionsClient +from google.cloud.orchestration.airflow.service_v1.services.image_versions.async_client import ImageVersionsAsyncClient + +from google.cloud.orchestration.airflow.service_v1.types.environments import AirflowMetadataRetentionPolicyConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import CheckUpgradeRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import CheckUpgradeResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import CloudDataLineageIntegration +from google.cloud.orchestration.airflow.service_v1.types.environments import CreateEnvironmentRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import CreateUserWorkloadsConfigMapRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import CreateUserWorkloadsSecretRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import DatabaseConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import DatabaseFailoverRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import DatabaseFailoverResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import DataRetentionConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import DeleteEnvironmentRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import DeleteUserWorkloadsConfigMapRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import DeleteUserWorkloadsSecretRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import EncryptionConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import Environment +from google.cloud.orchestration.airflow.service_v1.types.environments import EnvironmentConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import ExecuteAirflowCommandRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import ExecuteAirflowCommandResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import FetchDatabasePropertiesRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import FetchDatabasePropertiesResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import GetEnvironmentRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import GetUserWorkloadsConfigMapRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import GetUserWorkloadsSecretRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import IPAllocationPolicy +from google.cloud.orchestration.airflow.service_v1.types.environments import ListEnvironmentsRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import ListEnvironmentsResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import ListUserWorkloadsConfigMapsRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import ListUserWorkloadsConfigMapsResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import ListUserWorkloadsSecretsRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import ListUserWorkloadsSecretsResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import ListWorkloadsRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import ListWorkloadsResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import LoadSnapshotRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import LoadSnapshotResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import MaintenanceWindow +from google.cloud.orchestration.airflow.service_v1.types.environments import MasterAuthorizedNetworksConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import NetworkingConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import NodeConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import PollAirflowCommandRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import PollAirflowCommandResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import PrivateClusterConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import PrivateEnvironmentConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import RecoveryConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import SaveSnapshotRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import SaveSnapshotResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import ScheduledSnapshotsConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import SoftwareConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import StopAirflowCommandRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import StopAirflowCommandResponse +from google.cloud.orchestration.airflow.service_v1.types.environments import StorageConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import TaskLogsRetentionConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import UpdateEnvironmentRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import UpdateUserWorkloadsConfigMapRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import UpdateUserWorkloadsSecretRequest +from google.cloud.orchestration.airflow.service_v1.types.environments import UserWorkloadsConfigMap +from google.cloud.orchestration.airflow.service_v1.types.environments import UserWorkloadsSecret +from google.cloud.orchestration.airflow.service_v1.types.environments import WebServerConfig +from google.cloud.orchestration.airflow.service_v1.types.environments import WebServerNetworkAccessControl +from google.cloud.orchestration.airflow.service_v1.types.environments import WorkloadsConfig +from google.cloud.orchestration.airflow.service_v1.types.image_versions import ImageVersion +from google.cloud.orchestration.airflow.service_v1.types.image_versions import ListImageVersionsRequest +from google.cloud.orchestration.airflow.service_v1.types.image_versions import ListImageVersionsResponse +from google.cloud.orchestration.airflow.service_v1.types.operations import OperationMetadata + +__all__ = ('EnvironmentsClient', + 'EnvironmentsAsyncClient', + 'ImageVersionsClient', + 'ImageVersionsAsyncClient', + 'AirflowMetadataRetentionPolicyConfig', + 'CheckUpgradeRequest', + 'CheckUpgradeResponse', + 'CloudDataLineageIntegration', + 'CreateEnvironmentRequest', + 'CreateUserWorkloadsConfigMapRequest', + 'CreateUserWorkloadsSecretRequest', + 'DatabaseConfig', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'DataRetentionConfig', + 'DeleteEnvironmentRequest', + 'DeleteUserWorkloadsConfigMapRequest', + 'DeleteUserWorkloadsSecretRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'GetEnvironmentRequest', + 'GetUserWorkloadsConfigMapRequest', + 'GetUserWorkloadsSecretRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'ListUserWorkloadsConfigMapsRequest', + 'ListUserWorkloadsConfigMapsResponse', + 'ListUserWorkloadsSecretsRequest', + 'ListUserWorkloadsSecretsResponse', + 'ListWorkloadsRequest', + 'ListWorkloadsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'StorageConfig', + 'TaskLogsRetentionConfig', + 'UpdateEnvironmentRequest', + 'UpdateUserWorkloadsConfigMapRequest', + 'UpdateUserWorkloadsSecretRequest', + 'UserWorkloadsConfigMap', + 'UserWorkloadsSecret', + 'WebServerConfig', + 'WebServerNetworkAccessControl', + 'WorkloadsConfig', + 'ImageVersion', + 'ListImageVersionsRequest', + 'ListImageVersionsResponse', + 'OperationMetadata', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/gapic_version.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/py.typed b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/py.typed new file mode 100644 index 000000000000..f8ae386fb27e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-orchestration-airflow package uses inline types. diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py new file mode 100644 index 000000000000..b135afbc2b24 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.image_versions import ImageVersionsClient +from .services.image_versions import ImageVersionsAsyncClient + +from .types.environments import AirflowMetadataRetentionPolicyConfig +from .types.environments import CheckUpgradeRequest +from .types.environments import CheckUpgradeResponse +from .types.environments import CloudDataLineageIntegration +from .types.environments import CreateEnvironmentRequest +from .types.environments import CreateUserWorkloadsConfigMapRequest +from .types.environments import CreateUserWorkloadsSecretRequest +from .types.environments import DatabaseConfig +from .types.environments import DatabaseFailoverRequest +from .types.environments import DatabaseFailoverResponse +from .types.environments import DataRetentionConfig +from .types.environments import DeleteEnvironmentRequest +from .types.environments import DeleteUserWorkloadsConfigMapRequest +from .types.environments import DeleteUserWorkloadsSecretRequest +from .types.environments import EncryptionConfig +from .types.environments import Environment +from .types.environments import EnvironmentConfig +from .types.environments import ExecuteAirflowCommandRequest +from .types.environments import ExecuteAirflowCommandResponse +from .types.environments import FetchDatabasePropertiesRequest +from .types.environments import FetchDatabasePropertiesResponse +from .types.environments import GetEnvironmentRequest +from .types.environments import GetUserWorkloadsConfigMapRequest +from .types.environments import GetUserWorkloadsSecretRequest +from .types.environments import IPAllocationPolicy +from .types.environments import ListEnvironmentsRequest +from .types.environments import ListEnvironmentsResponse +from .types.environments import ListUserWorkloadsConfigMapsRequest +from .types.environments import ListUserWorkloadsConfigMapsResponse +from .types.environments import ListUserWorkloadsSecretsRequest +from .types.environments import ListUserWorkloadsSecretsResponse +from .types.environments import ListWorkloadsRequest +from .types.environments import ListWorkloadsResponse +from .types.environments import LoadSnapshotRequest +from .types.environments import LoadSnapshotResponse +from .types.environments import MaintenanceWindow +from .types.environments import MasterAuthorizedNetworksConfig +from .types.environments import NetworkingConfig +from .types.environments import NodeConfig +from .types.environments import PollAirflowCommandRequest +from .types.environments import PollAirflowCommandResponse +from .types.environments import PrivateClusterConfig +from .types.environments import PrivateEnvironmentConfig +from .types.environments import RecoveryConfig +from .types.environments import SaveSnapshotRequest +from .types.environments import SaveSnapshotResponse +from .types.environments import ScheduledSnapshotsConfig +from .types.environments import SoftwareConfig +from .types.environments import StopAirflowCommandRequest +from .types.environments import StopAirflowCommandResponse +from .types.environments import StorageConfig +from .types.environments import TaskLogsRetentionConfig +from .types.environments import UpdateEnvironmentRequest +from .types.environments import UpdateUserWorkloadsConfigMapRequest +from .types.environments import UpdateUserWorkloadsSecretRequest +from .types.environments import UserWorkloadsConfigMap +from .types.environments import UserWorkloadsSecret +from .types.environments import WebServerConfig +from .types.environments import WebServerNetworkAccessControl +from .types.environments import WorkloadsConfig +from .types.image_versions import ImageVersion +from .types.image_versions import ListImageVersionsRequest +from .types.image_versions import ListImageVersionsResponse +from .types.operations import OperationMetadata + +__all__ = ( + 'EnvironmentsAsyncClient', + 'ImageVersionsAsyncClient', +'AirflowMetadataRetentionPolicyConfig', +'CheckUpgradeRequest', +'CheckUpgradeResponse', +'CloudDataLineageIntegration', +'CreateEnvironmentRequest', +'CreateUserWorkloadsConfigMapRequest', +'CreateUserWorkloadsSecretRequest', +'DataRetentionConfig', +'DatabaseConfig', +'DatabaseFailoverRequest', +'DatabaseFailoverResponse', +'DeleteEnvironmentRequest', +'DeleteUserWorkloadsConfigMapRequest', +'DeleteUserWorkloadsSecretRequest', +'EncryptionConfig', +'Environment', +'EnvironmentConfig', +'EnvironmentsClient', +'ExecuteAirflowCommandRequest', +'ExecuteAirflowCommandResponse', +'FetchDatabasePropertiesRequest', +'FetchDatabasePropertiesResponse', +'GetEnvironmentRequest', +'GetUserWorkloadsConfigMapRequest', +'GetUserWorkloadsSecretRequest', +'IPAllocationPolicy', +'ImageVersion', +'ImageVersionsClient', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListImageVersionsRequest', +'ListImageVersionsResponse', +'ListUserWorkloadsConfigMapsRequest', +'ListUserWorkloadsConfigMapsResponse', +'ListUserWorkloadsSecretsRequest', +'ListUserWorkloadsSecretsResponse', +'ListWorkloadsRequest', +'ListWorkloadsResponse', +'LoadSnapshotRequest', +'LoadSnapshotResponse', +'MaintenanceWindow', +'MasterAuthorizedNetworksConfig', +'NetworkingConfig', +'NodeConfig', +'OperationMetadata', +'PollAirflowCommandRequest', +'PollAirflowCommandResponse', +'PrivateClusterConfig', +'PrivateEnvironmentConfig', +'RecoveryConfig', +'SaveSnapshotRequest', +'SaveSnapshotResponse', +'ScheduledSnapshotsConfig', +'SoftwareConfig', +'StopAirflowCommandRequest', +'StopAirflowCommandResponse', +'StorageConfig', +'TaskLogsRetentionConfig', +'UpdateEnvironmentRequest', +'UpdateUserWorkloadsConfigMapRequest', +'UpdateUserWorkloadsSecretRequest', +'UserWorkloadsConfigMap', +'UserWorkloadsSecret', +'WebServerConfig', +'WebServerNetworkAccessControl', +'WorkloadsConfig', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json new file mode 100644 index 000000000000..aca0f03a3f15 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json @@ -0,0 +1,422 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.orchestration.airflow.service_v1", + "protoPackage": "google.cloud.orchestration.airflow.service.v1", + "schema": "1.0", + "services": { + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CheckUpgrade": { + "methods": [ + "check_upgrade" + ] + }, + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "CreateUserWorkloadsConfigMap": { + "methods": [ + "create_user_workloads_config_map" + ] + }, + "CreateUserWorkloadsSecret": { + "methods": [ + "create_user_workloads_secret" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "DeleteUserWorkloadsConfigMap": { + "methods": [ + "delete_user_workloads_config_map" + ] + }, + "DeleteUserWorkloadsSecret": { + "methods": [ + "delete_user_workloads_secret" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetUserWorkloadsConfigMap": { + "methods": [ + "get_user_workloads_config_map" + ] + }, + "GetUserWorkloadsSecret": { + "methods": [ + "get_user_workloads_secret" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "ListUserWorkloadsConfigMaps": { + "methods": [ + "list_user_workloads_config_maps" + ] + }, + "ListUserWorkloadsSecrets": { + "methods": [ + "list_user_workloads_secrets" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + }, + "UpdateUserWorkloadsConfigMap": { + "methods": [ + "update_user_workloads_config_map" + ] + }, + "UpdateUserWorkloadsSecret": { + "methods": [ + "update_user_workloads_secret" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CheckUpgrade": { + "methods": [ + "check_upgrade" + ] + }, + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "CreateUserWorkloadsConfigMap": { + "methods": [ + "create_user_workloads_config_map" + ] + }, + "CreateUserWorkloadsSecret": { + "methods": [ + "create_user_workloads_secret" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "DeleteUserWorkloadsConfigMap": { + "methods": [ + "delete_user_workloads_config_map" + ] + }, + "DeleteUserWorkloadsSecret": { + "methods": [ + "delete_user_workloads_secret" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetUserWorkloadsConfigMap": { + "methods": [ + "get_user_workloads_config_map" + ] + }, + "GetUserWorkloadsSecret": { + "methods": [ + "get_user_workloads_secret" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "ListUserWorkloadsConfigMaps": { + "methods": [ + "list_user_workloads_config_maps" + ] + }, + "ListUserWorkloadsSecrets": { + "methods": [ + "list_user_workloads_secrets" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + }, + "UpdateUserWorkloadsConfigMap": { + "methods": [ + "update_user_workloads_config_map" + ] + }, + "UpdateUserWorkloadsSecret": { + "methods": [ + "update_user_workloads_secret" + ] + } + } + }, + "rest": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CheckUpgrade": { + "methods": [ + "check_upgrade" + ] + }, + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "CreateUserWorkloadsConfigMap": { + "methods": [ + "create_user_workloads_config_map" + ] + }, + "CreateUserWorkloadsSecret": { + "methods": [ + "create_user_workloads_secret" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "DeleteUserWorkloadsConfigMap": { + "methods": [ + "delete_user_workloads_config_map" + ] + }, + "DeleteUserWorkloadsSecret": { + "methods": [ + "delete_user_workloads_secret" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetUserWorkloadsConfigMap": { + "methods": [ + "get_user_workloads_config_map" + ] + }, + "GetUserWorkloadsSecret": { + "methods": [ + "get_user_workloads_secret" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "ListUserWorkloadsConfigMaps": { + "methods": [ + "list_user_workloads_config_maps" + ] + }, + "ListUserWorkloadsSecrets": { + "methods": [ + "list_user_workloads_secrets" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + }, + "UpdateUserWorkloadsConfigMap": { + "methods": [ + "update_user_workloads_config_map" + ] + }, + "UpdateUserWorkloadsSecret": { + "methods": [ + "update_user_workloads_secret" + ] + } + } + } + } + }, + "ImageVersions": { + "clients": { + "grpc": { + "libraryClient": "ImageVersionsClient", + "rpcs": { + "ListImageVersions": { + "methods": [ + "list_image_versions" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ImageVersionsAsyncClient", + "rpcs": { + "ListImageVersions": { + "methods": [ + "list_image_versions" + ] + } + } + }, + "rest": { + "libraryClient": "ImageVersionsClient", + "rpcs": { + "ListImageVersions": { + "methods": [ + "list_image_versions" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_version.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/py.typed b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/py.typed new file mode 100644 index 000000000000..f8ae386fb27e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-orchestration-airflow package uses inline types. diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/__init__.py new file mode 100644 index 000000000000..8aea3f820923 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/__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 EnvironmentsClient +from .async_client import EnvironmentsAsyncClient + +__all__ = ( + 'EnvironmentsClient', + 'EnvironmentsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py new file mode 100644 index 000000000000..f70a3fe39a6f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py @@ -0,0 +1,3216 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_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.orchestration.airflow.service_v1.services.environments import pagers +from google.cloud.orchestration.airflow.service_v1.types import environments +from google.cloud.orchestration.airflow.service_v1.types import operations +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 EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .client import EnvironmentsClient + +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 EnvironmentsAsyncClient: + """Managed Apache Airflow Environments.""" + + _client: EnvironmentsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = EnvironmentsClient._DEFAULT_UNIVERSE + + environment_path = staticmethod(EnvironmentsClient.environment_path) + parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) + user_workloads_config_map_path = staticmethod(EnvironmentsClient.user_workloads_config_map_path) + parse_user_workloads_config_map_path = staticmethod(EnvironmentsClient.parse_user_workloads_config_map_path) + user_workloads_secret_path = staticmethod(EnvironmentsClient.user_workloads_secret_path) + parse_user_workloads_secret_path = staticmethod(EnvironmentsClient.parse_user_workloads_secret_path) + common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) + common_project_path = staticmethod(EnvironmentsClient.common_project_path) + parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) + common_location_path = staticmethod(EnvironmentsClient.common_location_path) + parse_common_location_path = staticmethod(EnvironmentsClient.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: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, 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: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, 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 EnvironmentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EnvironmentsTransport: + """Returns the transport used by the client instance. + + Returns: + EnvironmentsTransport: 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 = EnvironmentsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EnvironmentsTransport, Callable[..., EnvironmentsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the environments 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,EnvironmentsTransport,Callable[..., EnvironmentsTransport]]]): + 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 EnvironmentsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EnvironmentsClient( + 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.orchestration.airflow.service_v1.EnvironmentsAsyncClient`.", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "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.orchestration.airflow.service.v1.Environments", + "credentialsType": None, + } + ) + + async def create_environment(self, + request: Optional[Union[environments.CreateEnvironmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + environment: Optional[environments.Environment] = 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"""Create a new environment. + + .. 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.orchestration.airflow import service_v1 + + async def sample_create_environment(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.CreateEnvironmentRequest( + ) + + # Make the request + operation = client.create_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.CreateEnvironmentRequest, dict]]): + The request object. Create a new environment. + parent (:class:`str`): + The parent must be of the form + "projects/{projectId}/locations/{locationId}". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (:class:`google.cloud.orchestration.airflow.service_v1.types.Environment`): + The environment to create. + This corresponds to the ``environment`` 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.orchestration.airflow.service_v1.types.Environment` + An environment for running orchestration tasks. + + """ + # 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. + flattened_params = [parent, environment] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateEnvironmentRequest): + request = environments.CreateEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if environment is not None: + request.environment = environment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_environment] + + # 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, + environments.Environment, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_environment(self, + request: Optional[Union[environments.GetEnvironmentRequest, 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]]] = (), + ) -> environments.Environment: + r"""Get an existing environment. + + .. 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.orchestration.airflow import service_v1 + + async def sample_get_environment(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.GetEnvironmentRequest( + ) + + # Make the request + response = await client.get_environment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.GetEnvironmentRequest, dict]]): + The request object. Get an environment. + name (:class:`str`): + The resource name of the environment + to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1.types.Environment: + An environment for running + orchestration tasks. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetEnvironmentRequest): + request = environments.GetEnvironmentRequest(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_environment] + + # 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_environments(self, + request: Optional[Union[environments.ListEnvironmentsRequest, 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.ListEnvironmentsAsyncPager: + r"""List environments. + + .. 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.orchestration.airflow import service_v1 + + async def sample_list_environments(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ListEnvironmentsRequest( + ) + + # Make the request + page_result = client.list_environments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest, dict]]): + The request object. List environments in a project and + location. + parent (:class:`str`): + List environments in the given + project and location, in the form: + "projects/{projectId}/locations/{locationId}" + + 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.orchestration.airflow.service_v1.services.environments.pagers.ListEnvironmentsAsyncPager: + The environments in a project and + location. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListEnvironmentsRequest): + request = environments.ListEnvironmentsRequest(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_environments] + + # 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.ListEnvironmentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_environment(self, + request: Optional[Union[environments.UpdateEnvironmentRequest, dict]] = None, + *, + name: Optional[str] = None, + environment: Optional[environments.Environment] = 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"""Update an environment. + + .. 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.orchestration.airflow import service_v1 + + async def sample_update_environment(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.UpdateEnvironmentRequest( + ) + + # Make the request + operation = client.update_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.UpdateEnvironmentRequest, dict]]): + The request object. Update an environment. + name (:class:`str`): + The relative resource name of the + environment to update, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (:class:`google.cloud.orchestration.airflow.service_v1.types.Environment`): + A patch environment. Fields specified by the + ``updateMask`` will be copied from the patch environment + into the environment under update. + + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A comma-separated list of paths, relative to + ``Environment``, of fields to update. For example, to + set the version of scikit-learn to install in the + environment to 0.19.0 and to remove an existing + installation of numpy, the ``updateMask`` parameter + would include the following two ``paths`` values: + "config.softwareConfig.pypiPackages.scikit-learn" and + "config.softwareConfig.pypiPackages.numpy". The included + patch environment would specify the scikit-learn version + as follows: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "scikit-learn":"==0.19.0" + } + } + } + } + + Note that in the above example, any existing PyPI + packages other than scikit-learn and numpy will be + unaffected. + + Only one update type may be included in a single + request's ``updateMask``. For example, one cannot update + both the PyPI packages and labels in the same request. + However, it is possible to update multiple members of a + map field simultaneously in the same request. For + example, to set the labels "label1" and "label2" while + clearing "label3" (assuming it already exists), one can + provide the paths "labels.label1", "labels.label2", and + "labels.label3" and populate the patch environment as + follows: + + :: + + { + "labels":{ + "label1":"new-label1-value" + "label2":"new-label2-value" + } + } + + Note that in the above example, any existing labels that + are not included in the ``updateMask`` will be + unaffected. + + It is also possible to replace an entire map field by + providing the map field's path in the ``updateMask``. + The new value of the field will be that which is + provided in the patch environment. For example, to + delete all pre-existing user-specified PyPI packages and + install botocore at version 1.7.14, the ``updateMask`` + would contain the path + "config.softwareConfig.pypiPackages", and the patch + environment would be the following: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "botocore":"==1.7.14" + } + } + } + } + + **Note:** Only the following fields can be updated: + + - ``config.softwareConfig.pypiPackages`` + + - Replace all custom custom PyPI packages. If a + replacement package map is not included in + ``environment``, all custom PyPI packages are + cleared. It is an error to provide both this mask + and a mask specifying an individual package. + + - ``config.softwareConfig.pypiPackages.``\ packagename + + - Update the custom PyPI package *packagename*, + preserving other packages. To delete the package, + include it in ``updateMask``, and omit the mapping + for it in + ``environment.config.softwareConfig.pypiPackages``. + It is an error to provide both a mask of this form + and the ``config.softwareConfig.pypiPackages`` + mask. + + - ``labels`` + + - Replace all environment labels. If a replacement + labels map is not included in ``environment``, all + labels are cleared. It is an error to provide both + this mask and a mask specifying one or more + individual labels. + + - ``labels.``\ labelName + + - Set the label named *labelName*, while preserving + other labels. To delete the label, include it in + ``updateMask`` and omit its mapping in + ``environment.labels``. It is an error to provide + both a mask of this form and the ``labels`` mask. + + - ``config.nodeCount`` + + - Horizontally scale the number of nodes in the + environment. An integer greater than or equal to 3 + must be provided in the ``config.nodeCount`` + field. Supported for Cloud Composer environments + in versions composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerNetworkAccessControl`` + + - Replace the environment's current + ``WebServerNetworkAccessControl``. + + - ``config.softwareConfig.airflowConfigOverrides`` + + - Replace all Apache Airflow config overrides. If a + replacement config overrides map is not included + in ``environment``, all config overrides are + cleared. It is an error to provide both this mask + and a mask specifying one or more individual + config overrides. + + - ``config.softwareConfig.airflowConfigOverrides.``\ section-name + + - Override the Apache Airflow config property *name* + in the section named *section*, preserving other + properties. To delete the property override, + include it in ``updateMask`` and omit its mapping + in + ``environment.config.softwareConfig.airflowConfigOverrides``. + It is an error to provide both a mask of this form + and the + ``config.softwareConfig.airflowConfigOverrides`` + mask. + + - ``config.softwareConfig.envVariables`` + + - Replace all environment variables. If a + replacement environment variable map is not + included in ``environment``, all custom + environment variables are cleared. + + - ``config.softwareConfig.schedulerCount`` + + - Horizontally scale the number of schedulers in + Airflow. A positive integer not greater than the + number of nodes must be provided in the + ``config.softwareConfig.schedulerCount`` field. + Supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-2.*.*. + + - ``config.databaseConfig.machineType`` + + - Cloud SQL machine type used by Airflow database. + It has to be one of: db-n1-standard-2, + db-n1-standard-4, db-n1-standard-8 or + db-n1-standard-16. Supported for Cloud Composer + environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerConfig.machineType`` + + - Machine type on which Airflow web server is + running. It has to be one of: + composer-n1-webserver-2, composer-n1-webserver-4 + or composer-n1-webserver-8. Supported for Cloud + Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + 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.orchestration.airflow.service_v1.types.Environment` + An environment for running orchestration tasks. + + """ + # 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. + flattened_params = [name, environment, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateEnvironmentRequest): + request = environments.UpdateEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if environment is not None: + request.environment = environment + 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_environment] + + # 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, + environments.Environment, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_environment(self, + request: Optional[Union[environments.DeleteEnvironmentRequest, 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"""Delete an environment. + + .. 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.orchestration.airflow import service_v1 + + async def sample_delete_environment(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.DeleteEnvironmentRequest( + ) + + # Make the request + operation = client.delete_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.DeleteEnvironmentRequest, dict]]): + The request object. Delete an environment. + name (:class:`str`): + The environment to delete, in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteEnvironmentRequest): + request = environments.DeleteEnvironmentRequest(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_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def execute_airflow_command(self, + request: Optional[Union[environments.ExecuteAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.ExecuteAirflowCommandResponse: + r"""Executes Airflow CLI command. + + .. 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.orchestration.airflow import service_v1 + + async def sample_execute_airflow_command(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ExecuteAirflowCommandRequest( + ) + + # Make the request + response = await client.execute_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandRequest, dict]]): + The request object. Execute Airflow Command request. + 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.orchestration.airflow.service_v1.types.ExecuteAirflowCommandResponse: + Response to + ExecuteAirflowCommandRequest. + + """ + # 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, environments.ExecuteAirflowCommandRequest): + request = environments.ExecuteAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.execute_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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 stop_airflow_command(self, + request: Optional[Union[environments.StopAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.StopAirflowCommandResponse: + r"""Stops Airflow CLI command execution. + + .. 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.orchestration.airflow import service_v1 + + async def sample_stop_airflow_command(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.StopAirflowCommandRequest( + ) + + # Make the request + response = await client.stop_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandRequest, dict]]): + The request object. Stop Airflow Command request. + 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.orchestration.airflow.service_v1.types.StopAirflowCommandResponse: + Response to + StopAirflowCommandRequest. + + """ + # 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, environments.StopAirflowCommandRequest): + request = environments.StopAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.stop_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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 poll_airflow_command(self, + request: Optional[Union[environments.PollAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.PollAirflowCommandResponse: + r"""Polls Airflow CLI command execution and fetches logs. + + .. 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.orchestration.airflow import service_v1 + + async def sample_poll_airflow_command(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.PollAirflowCommandRequest( + ) + + # Make the request + response = await client.poll_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandRequest, dict]]): + The request object. Poll Airflow Command request. + 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.orchestration.airflow.service_v1.types.PollAirflowCommandResponse: + Response to + PollAirflowCommandRequest. + + """ + # 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, environments.PollAirflowCommandRequest): + request = environments.PollAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.poll_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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_workloads(self, + request: Optional[Union[environments.ListWorkloadsRequest, 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.ListWorkloadsAsyncPager: + r"""Lists workloads in a Cloud Composer environment. Workload is a + unit that runs a single Composer component. + + This method is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_list_workloads(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest, dict]]): + The request object. Request for listing workloads in a + Cloud Composer environment. + parent (:class:`str`): + Required. The environment name to get + workloads for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1.services.environments.pagers.ListWorkloadsAsyncPager: + Response to ListWorkloadsRequest. + + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListWorkloadsRequest): + request = environments.ListWorkloadsRequest(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_workloads] + + # 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.ListWorkloadsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def check_upgrade(self, + request: Optional[Union[environments.CheckUpgradeRequest, dict]] = 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"""Check if an upgrade operation on the environment will + succeed. + In case of problems detailed info can be found in the + returned 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.orchestration.airflow import service_v1 + + async def sample_check_upgrade(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.CheckUpgradeRequest( + environment="environment_value", + ) + + # Make the request + operation = client.check_upgrade(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.CheckUpgradeRequest, dict]]): + The request object. Request to check whether image + upgrade will succeed. + 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.orchestration.airflow.service_v1.types.CheckUpgradeResponse` Message containing information about the result of an upgrade check + operation. + + """ + # 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, environments.CheckUpgradeRequest): + request = environments.CheckUpgradeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.check_upgrade] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.CheckUpgradeResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_user_workloads_secret(self, + request: Optional[Union[environments.CreateUserWorkloadsSecretRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_create_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.CreateUserWorkloadsSecretRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsSecretRequest, dict]]): + The request object. Create user workloads Secret request. + parent (:class:`str`): + Required. The environment name to + create a Secret for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_workloads_secret (:class:`google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret`): + Required. User workloads Secret to + create. + + This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [parent, user_workloads_secret] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateUserWorkloadsSecretRequest): + request = environments.CreateUserWorkloadsSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_workloads_secret is not None: + request.user_workloads_secret = user_workloads_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_user_workloads_secret] + + # 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 get_user_workloads_secret(self, + request: Optional[Union[environments.GetUserWorkloadsSecretRequest, 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]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Gets an existing user workloads Secret. Values of the "data" + field in the response are cleared. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_get_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.GetUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsSecretRequest, dict]]): + The request object. Get user workloads Secret request. + name (:class:`str`): + Required. The resource name of the + Secret to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" + + 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetUserWorkloadsSecretRequest): + request = environments.GetUserWorkloadsSecretRequest(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_user_workloads_secret] + + # 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_user_workloads_secrets(self, + request: Optional[Union[environments.ListUserWorkloadsSecretsRequest, 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.ListUserWorkloadsSecretsAsyncPager: + r"""Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_list_user_workloads_secrets(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ListUserWorkloadsSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_secrets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest, dict]]): + The request object. List user workloads Secrets request. + parent (:class:`str`): + Required. List Secrets in the given + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsSecretsAsyncPager: + The user workloads Secrets for a + given environment. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListUserWorkloadsSecretsRequest): + request = environments.ListUserWorkloadsSecretsRequest(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_user_workloads_secrets] + + # 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.ListUserWorkloadsSecretsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_user_workloads_secret(self, + request: Optional[Union[environments.UpdateUserWorkloadsSecretRequest, dict]] = None, + *, + user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_update_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.UpdateUserWorkloadsSecretRequest( + ) + + # Make the request + response = await client.update_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsSecretRequest, dict]]): + The request object. Update user workloads Secret request. + user_workloads_secret (:class:`google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret`): + Optional. User workloads Secret to + override. + + This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [user_workloads_secret] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateUserWorkloadsSecretRequest): + request = environments.UpdateUserWorkloadsSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_workloads_secret is not None: + request.user_workloads_secret = user_workloads_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_user_workloads_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user_workloads_secret.name", request.user_workloads_secret.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_user_workloads_secret(self, + request: Optional[Union[environments.DeleteUserWorkloadsSecretRequest, 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]]] = (), + ) -> None: + r"""Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_delete_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.DeleteUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_workloads_secret(request=request) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsSecretRequest, dict]]): + The request object. Delete user workloads Secret request. + name (:class:`str`): + Required. The Secret to delete, in + the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" + + 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`. + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteUserWorkloadsSecretRequest): + request = environments.DeleteUserWorkloadsSecretRequest(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_user_workloads_secret] + + # 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 create_user_workloads_config_map(self, + request: Optional[Union[environments.CreateUserWorkloadsConfigMapRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_create_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.CreateUserWorkloadsConfigMapRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsConfigMapRequest, dict]]): + The request object. Create user workloads ConfigMap + request. + parent (:class:`str`): + Required. The environment name to + create a ConfigMap for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_workloads_config_map (:class:`google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap`): + Required. User workloads ConfigMap to + create. + + This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [parent, user_workloads_config_map] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateUserWorkloadsConfigMapRequest): + request = environments.CreateUserWorkloadsConfigMapRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_workloads_config_map is not None: + request.user_workloads_config_map = user_workloads_config_map + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_user_workloads_config_map] + + # 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 get_user_workloads_config_map(self, + request: Optional[Union[environments.GetUserWorkloadsConfigMapRequest, 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]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_get_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.GetUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsConfigMapRequest, dict]]): + The request object. Get user workloads ConfigMap request. + name (:class:`str`): + Required. The resource name of the + ConfigMap to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" + + 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetUserWorkloadsConfigMapRequest): + request = environments.GetUserWorkloadsConfigMapRequest(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_user_workloads_config_map] + + # 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_user_workloads_config_maps(self, + request: Optional[Union[environments.ListUserWorkloadsConfigMapsRequest, 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.ListUserWorkloadsConfigMapsAsyncPager: + r"""Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_list_user_workloads_config_maps(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ListUserWorkloadsConfigMapsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_config_maps(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest, dict]]): + The request object. List user workloads ConfigMaps + request. + parent (:class:`str`): + Required. List ConfigMaps in the + given environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsConfigMapsAsyncPager: + The user workloads ConfigMaps for a + given environment. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListUserWorkloadsConfigMapsRequest): + request = environments.ListUserWorkloadsConfigMapsRequest(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_user_workloads_config_maps] + + # 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.ListUserWorkloadsConfigMapsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_user_workloads_config_map(self, + request: Optional[Union[environments.UpdateUserWorkloadsConfigMapRequest, dict]] = None, + *, + user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_update_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.UpdateUserWorkloadsConfigMapRequest( + ) + + # Make the request + response = await client.update_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsConfigMapRequest, dict]]): + The request object. Update user workloads ConfigMap + request. + user_workloads_config_map (:class:`google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap`): + Optional. User workloads ConfigMap to + override. + + This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [user_workloads_config_map] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateUserWorkloadsConfigMapRequest): + request = environments.UpdateUserWorkloadsConfigMapRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_workloads_config_map is not None: + request.user_workloads_config_map = user_workloads_config_map + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_user_workloads_config_map] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user_workloads_config_map.name", request.user_workloads_config_map.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_user_workloads_config_map(self, + request: Optional[Union[environments.DeleteUserWorkloadsConfigMapRequest, 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]]] = (), + ) -> None: + r"""Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + async def sample_delete_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.DeleteUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_workloads_config_map(request=request) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsConfigMapRequest, dict]]): + The request object. Delete user workloads ConfigMap + request. + name (:class:`str`): + Required. The ConfigMap to delete, in + the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" + + 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`. + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteUserWorkloadsConfigMapRequest): + request = environments.DeleteUserWorkloadsConfigMapRequest(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_user_workloads_config_map] + + # 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 save_snapshot(self, + request: Optional[Union[environments.SaveSnapshotRequest, dict]] = 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 snapshots of a Cloud Composer environment. + + As a result of this operation, snapshot of environment's + state is stored in a location specified in the + SaveSnapshotRequest. + + .. 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.orchestration.airflow import service_v1 + + async def sample_save_snapshot(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.SaveSnapshotRequest( + ) + + # Make the request + operation = client.save_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.SaveSnapshotRequest, dict]]): + The request object. Request to create a snapshot of a + Cloud Composer environment. + 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.orchestration.airflow.service_v1.types.SaveSnapshotResponse` + Response to SaveSnapshotRequest. + + """ + # 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, environments.SaveSnapshotRequest): + request = environments.SaveSnapshotRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.save_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.SaveSnapshotResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def load_snapshot(self, + request: Optional[Union[environments.LoadSnapshotRequest, dict]] = 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"""Loads a snapshot of a Cloud Composer environment. + + As a result of this operation, a snapshot of + environment's specified in LoadSnapshotRequest is loaded + into the environment. + + .. 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.orchestration.airflow import service_v1 + + async def sample_load_snapshot(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.LoadSnapshotRequest( + ) + + # Make the request + operation = client.load_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.LoadSnapshotRequest, dict]]): + The request object. Request to load a snapshot into a + Cloud Composer environment. + 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.orchestration.airflow.service_v1.types.LoadSnapshotResponse` + Response to LoadSnapshotRequest. + + """ + # 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, environments.LoadSnapshotRequest): + request = environments.LoadSnapshotRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.load_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.LoadSnapshotResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def database_failover(self, + request: Optional[Union[environments.DatabaseFailoverRequest, dict]] = 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"""Triggers database failover (only for highly resilient + environments). + + .. 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.orchestration.airflow import service_v1 + + async def sample_database_failover(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.DatabaseFailoverRequest( + ) + + # Make the request + operation = client.database_failover(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.DatabaseFailoverRequest, dict]]): + The request object. Request to trigger database failover + (only for highly resilient + environments). + 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.orchestration.airflow.service_v1.types.DatabaseFailoverResponse` + Response for DatabaseFailoverRequest. + + """ + # 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, environments.DatabaseFailoverRequest): + request = environments.DatabaseFailoverRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.database_failover] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.DatabaseFailoverResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def fetch_database_properties(self, + request: Optional[Union[environments.FetchDatabasePropertiesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.FetchDatabasePropertiesResponse: + r"""Fetches database properties. + + .. 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.orchestration.airflow import service_v1 + + async def sample_fetch_database_properties(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.FetchDatabasePropertiesRequest( + environment="environment_value", + ) + + # Make the request + response = await client.fetch_database_properties(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesRequest, dict]]): + The request object. Request to fetch properties of + environment's database. + 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.orchestration.airflow.service_v1.types.FetchDatabasePropertiesResponse: + Response for + FetchDatabasePropertiesRequest. + + """ + # 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, environments.FetchDatabasePropertiesRequest): + request = environments.FetchDatabasePropertiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.fetch_database_properties] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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 __aenter__(self) -> "EnvironmentsAsyncClient": + 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__ = ( + "EnvironmentsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py new file mode 100644 index 000000000000..9b20c3657db6 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py @@ -0,0 +1,3589 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +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.orchestration.airflow.service_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.orchestration.airflow.service_v1.services.environments import pagers +from google.cloud.orchestration.airflow.service_v1.types import environments +from google.cloud.orchestration.airflow.service_v1.types import operations +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 EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EnvironmentsGrpcTransport +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .transports.rest import EnvironmentsRestTransport + + +class EnvironmentsClientMeta(type): + """Metaclass for the Environments 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[EnvironmentsTransport]] + _transport_registry["grpc"] = EnvironmentsGrpcTransport + _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport + _transport_registry["rest"] = EnvironmentsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[EnvironmentsTransport]: + """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 EnvironmentsClient(metaclass=EnvironmentsClientMeta): + """Managed Apache Airflow Environments.""" + + @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 = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "composer.{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: + EnvironmentsClient: 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: + EnvironmentsClient: 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) -> EnvironmentsTransport: + """Returns the transport used by the client instance. + + Returns: + EnvironmentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def environment_path(project: str,location: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/environments/{environment}".format(project=project, location=location, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_workloads_config_map_path(project: str,location: str,environment: str,user_workloads_config_map: str,) -> str: + """Returns a fully-qualified user_workloads_config_map string.""" + return "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsConfigMaps/{user_workloads_config_map}".format(project=project, location=location, environment=environment, user_workloads_config_map=user_workloads_config_map, ) + + @staticmethod + def parse_user_workloads_config_map_path(path: str) -> Dict[str,str]: + """Parses a user_workloads_config_map path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)/userWorkloadsConfigMaps/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_workloads_secret_path(project: str,location: str,environment: str,user_workloads_secret: str,) -> str: + """Returns a fully-qualified user_workloads_secret string.""" + return "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsSecrets/{user_workloads_secret}".format(project=project, location=location, environment=environment, user_workloads_secret=user_workloads_secret, ) + + @staticmethod + def parse_user_workloads_secret_path(path: str) -> Dict[str,str]: + """Parses a user_workloads_secret path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)/userWorkloadsSecrets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = EnvironmentsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = EnvironmentsClient._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 = EnvironmentsClient._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 + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @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, EnvironmentsTransport, Callable[..., EnvironmentsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the environments 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,EnvironmentsTransport,Callable[..., EnvironmentsTransport]]]): + 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 EnvironmentsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = EnvironmentsClient._read_environment_variables() + self._client_cert_source = EnvironmentsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = EnvironmentsClient._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, EnvironmentsTransport) + if transport_provided: + # transport is a EnvironmentsTransport 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(EnvironmentsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + EnvironmentsClient._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[EnvironmentsTransport], Callable[..., EnvironmentsTransport]] = ( + EnvironmentsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., EnvironmentsTransport], 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.orchestration.airflow.service_v1.EnvironmentsClient`.", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "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.orchestration.airflow.service.v1.Environments", + "credentialsType": None, + } + ) + + def create_environment(self, + request: Optional[Union[environments.CreateEnvironmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + environment: Optional[environments.Environment] = 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"""Create a new environment. + + .. 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.orchestration.airflow import service_v1 + + def sample_create_environment(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.CreateEnvironmentRequest( + ) + + # Make the request + operation = client.create_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.CreateEnvironmentRequest, dict]): + The request object. Create a new environment. + parent (str): + The parent must be of the form + "projects/{projectId}/locations/{locationId}". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (google.cloud.orchestration.airflow.service_v1.types.Environment): + The environment to create. + This corresponds to the ``environment`` 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.orchestration.airflow.service_v1.types.Environment` + An environment for running orchestration tasks. + + """ + # 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. + flattened_params = [parent, environment] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateEnvironmentRequest): + request = environments.CreateEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if environment is not None: + request.environment = environment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # 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, + environments.Environment, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_environment(self, + request: Optional[Union[environments.GetEnvironmentRequest, 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]]] = (), + ) -> environments.Environment: + r"""Get an existing environment. + + .. 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.orchestration.airflow import service_v1 + + def sample_get_environment(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.GetEnvironmentRequest( + ) + + # Make the request + response = client.get_environment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.GetEnvironmentRequest, dict]): + The request object. Get an environment. + name (str): + The resource name of the environment + to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1.types.Environment: + An environment for running + orchestration tasks. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetEnvironmentRequest): + request = environments.GetEnvironmentRequest(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_environment] + + # 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_environments(self, + request: Optional[Union[environments.ListEnvironmentsRequest, 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.ListEnvironmentsPager: + r"""List environments. + + .. 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.orchestration.airflow import service_v1 + + def sample_list_environments(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.ListEnvironmentsRequest( + ) + + # Make the request + page_result = client.list_environments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest, dict]): + The request object. List environments in a project and + location. + parent (str): + List environments in the given + project and location, in the form: + "projects/{projectId}/locations/{locationId}" + + 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.orchestration.airflow.service_v1.services.environments.pagers.ListEnvironmentsPager: + The environments in a project and + location. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListEnvironmentsRequest): + request = environments.ListEnvironmentsRequest(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_environments] + + # 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.ListEnvironmentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_environment(self, + request: Optional[Union[environments.UpdateEnvironmentRequest, dict]] = None, + *, + name: Optional[str] = None, + environment: Optional[environments.Environment] = 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"""Update an environment. + + .. 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.orchestration.airflow import service_v1 + + def sample_update_environment(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.UpdateEnvironmentRequest( + ) + + # Make the request + operation = client.update_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.UpdateEnvironmentRequest, dict]): + The request object. Update an environment. + name (str): + The relative resource name of the + environment to update, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (google.cloud.orchestration.airflow.service_v1.types.Environment): + A patch environment. Fields specified by the + ``updateMask`` will be copied from the patch environment + into the environment under update. + + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of paths, relative to + ``Environment``, of fields to update. For example, to + set the version of scikit-learn to install in the + environment to 0.19.0 and to remove an existing + installation of numpy, the ``updateMask`` parameter + would include the following two ``paths`` values: + "config.softwareConfig.pypiPackages.scikit-learn" and + "config.softwareConfig.pypiPackages.numpy". The included + patch environment would specify the scikit-learn version + as follows: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "scikit-learn":"==0.19.0" + } + } + } + } + + Note that in the above example, any existing PyPI + packages other than scikit-learn and numpy will be + unaffected. + + Only one update type may be included in a single + request's ``updateMask``. For example, one cannot update + both the PyPI packages and labels in the same request. + However, it is possible to update multiple members of a + map field simultaneously in the same request. For + example, to set the labels "label1" and "label2" while + clearing "label3" (assuming it already exists), one can + provide the paths "labels.label1", "labels.label2", and + "labels.label3" and populate the patch environment as + follows: + + :: + + { + "labels":{ + "label1":"new-label1-value" + "label2":"new-label2-value" + } + } + + Note that in the above example, any existing labels that + are not included in the ``updateMask`` will be + unaffected. + + It is also possible to replace an entire map field by + providing the map field's path in the ``updateMask``. + The new value of the field will be that which is + provided in the patch environment. For example, to + delete all pre-existing user-specified PyPI packages and + install botocore at version 1.7.14, the ``updateMask`` + would contain the path + "config.softwareConfig.pypiPackages", and the patch + environment would be the following: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "botocore":"==1.7.14" + } + } + } + } + + **Note:** Only the following fields can be updated: + + - ``config.softwareConfig.pypiPackages`` + + - Replace all custom custom PyPI packages. If a + replacement package map is not included in + ``environment``, all custom PyPI packages are + cleared. It is an error to provide both this mask + and a mask specifying an individual package. + + - ``config.softwareConfig.pypiPackages.``\ packagename + + - Update the custom PyPI package *packagename*, + preserving other packages. To delete the package, + include it in ``updateMask``, and omit the mapping + for it in + ``environment.config.softwareConfig.pypiPackages``. + It is an error to provide both a mask of this form + and the ``config.softwareConfig.pypiPackages`` + mask. + + - ``labels`` + + - Replace all environment labels. If a replacement + labels map is not included in ``environment``, all + labels are cleared. It is an error to provide both + this mask and a mask specifying one or more + individual labels. + + - ``labels.``\ labelName + + - Set the label named *labelName*, while preserving + other labels. To delete the label, include it in + ``updateMask`` and omit its mapping in + ``environment.labels``. It is an error to provide + both a mask of this form and the ``labels`` mask. + + - ``config.nodeCount`` + + - Horizontally scale the number of nodes in the + environment. An integer greater than or equal to 3 + must be provided in the ``config.nodeCount`` + field. Supported for Cloud Composer environments + in versions composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerNetworkAccessControl`` + + - Replace the environment's current + ``WebServerNetworkAccessControl``. + + - ``config.softwareConfig.airflowConfigOverrides`` + + - Replace all Apache Airflow config overrides. If a + replacement config overrides map is not included + in ``environment``, all config overrides are + cleared. It is an error to provide both this mask + and a mask specifying one or more individual + config overrides. + + - ``config.softwareConfig.airflowConfigOverrides.``\ section-name + + - Override the Apache Airflow config property *name* + in the section named *section*, preserving other + properties. To delete the property override, + include it in ``updateMask`` and omit its mapping + in + ``environment.config.softwareConfig.airflowConfigOverrides``. + It is an error to provide both a mask of this form + and the + ``config.softwareConfig.airflowConfigOverrides`` + mask. + + - ``config.softwareConfig.envVariables`` + + - Replace all environment variables. If a + replacement environment variable map is not + included in ``environment``, all custom + environment variables are cleared. + + - ``config.softwareConfig.schedulerCount`` + + - Horizontally scale the number of schedulers in + Airflow. A positive integer not greater than the + number of nodes must be provided in the + ``config.softwareConfig.schedulerCount`` field. + Supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-2.*.*. + + - ``config.databaseConfig.machineType`` + + - Cloud SQL machine type used by Airflow database. + It has to be one of: db-n1-standard-2, + db-n1-standard-4, db-n1-standard-8 or + db-n1-standard-16. Supported for Cloud Composer + environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerConfig.machineType`` + + - Machine type on which Airflow web server is + running. It has to be one of: + composer-n1-webserver-2, composer-n1-webserver-4 + or composer-n1-webserver-8. Supported for Cloud + Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + 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.orchestration.airflow.service_v1.types.Environment` + An environment for running orchestration tasks. + + """ + # 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. + flattened_params = [name, environment, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateEnvironmentRequest): + request = environments.UpdateEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if environment is not None: + request.environment = environment + 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_environment] + + # 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, + environments.Environment, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_environment(self, + request: Optional[Union[environments.DeleteEnvironmentRequest, 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"""Delete an environment. + + .. 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.orchestration.airflow import service_v1 + + def sample_delete_environment(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.DeleteEnvironmentRequest( + ) + + # Make the request + operation = client.delete_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.DeleteEnvironmentRequest, dict]): + The request object. Delete an environment. + name (str): + The environment to delete, in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteEnvironmentRequest): + request = environments.DeleteEnvironmentRequest(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_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def execute_airflow_command(self, + request: Optional[Union[environments.ExecuteAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.ExecuteAirflowCommandResponse: + r"""Executes Airflow CLI command. + + .. 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.orchestration.airflow import service_v1 + + def sample_execute_airflow_command(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.ExecuteAirflowCommandRequest( + ) + + # Make the request + response = client.execute_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandRequest, dict]): + The request object. Execute Airflow Command request. + retry (google.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.orchestration.airflow.service_v1.types.ExecuteAirflowCommandResponse: + Response to + ExecuteAirflowCommandRequest. + + """ + # 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, environments.ExecuteAirflowCommandRequest): + request = environments.ExecuteAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.execute_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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 stop_airflow_command(self, + request: Optional[Union[environments.StopAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.StopAirflowCommandResponse: + r"""Stops Airflow CLI command execution. + + .. 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.orchestration.airflow import service_v1 + + def sample_stop_airflow_command(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.StopAirflowCommandRequest( + ) + + # Make the request + response = client.stop_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandRequest, dict]): + The request object. Stop Airflow Command request. + retry (google.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.orchestration.airflow.service_v1.types.StopAirflowCommandResponse: + Response to + StopAirflowCommandRequest. + + """ + # 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, environments.StopAirflowCommandRequest): + request = environments.StopAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stop_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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 poll_airflow_command(self, + request: Optional[Union[environments.PollAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.PollAirflowCommandResponse: + r"""Polls Airflow CLI command execution and fetches logs. + + .. 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.orchestration.airflow import service_v1 + + def sample_poll_airflow_command(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.PollAirflowCommandRequest( + ) + + # Make the request + response = client.poll_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandRequest, dict]): + The request object. Poll Airflow Command request. + retry (google.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.orchestration.airflow.service_v1.types.PollAirflowCommandResponse: + Response to + PollAirflowCommandRequest. + + """ + # 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, environments.PollAirflowCommandRequest): + request = environments.PollAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.poll_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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_workloads(self, + request: Optional[Union[environments.ListWorkloadsRequest, 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.ListWorkloadsPager: + r"""Lists workloads in a Cloud Composer environment. Workload is a + unit that runs a single Composer component. + + This method is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_list_workloads(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest, dict]): + The request object. Request for listing workloads in a + Cloud Composer environment. + parent (str): + Required. The environment name to get + workloads for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1.services.environments.pagers.ListWorkloadsPager: + Response to ListWorkloadsRequest. + + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListWorkloadsRequest): + request = environments.ListWorkloadsRequest(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_workloads] + + # 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.ListWorkloadsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def check_upgrade(self, + request: Optional[Union[environments.CheckUpgradeRequest, dict]] = 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"""Check if an upgrade operation on the environment will + succeed. + In case of problems detailed info can be found in the + returned 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.orchestration.airflow import service_v1 + + def sample_check_upgrade(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.CheckUpgradeRequest( + environment="environment_value", + ) + + # Make the request + operation = client.check_upgrade(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.CheckUpgradeRequest, dict]): + The request object. Request to check whether image + upgrade will succeed. + retry (google.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.orchestration.airflow.service_v1.types.CheckUpgradeResponse` Message containing information about the result of an upgrade check + operation. + + """ + # 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, environments.CheckUpgradeRequest): + request = environments.CheckUpgradeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.check_upgrade] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.CheckUpgradeResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_user_workloads_secret(self, + request: Optional[Union[environments.CreateUserWorkloadsSecretRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_create_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.CreateUserWorkloadsSecretRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsSecretRequest, dict]): + The request object. Create user workloads Secret request. + parent (str): + Required. The environment name to + create a Secret for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_workloads_secret (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret): + Required. User workloads Secret to + create. + + This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [parent, user_workloads_secret] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateUserWorkloadsSecretRequest): + request = environments.CreateUserWorkloadsSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_workloads_secret is not None: + request.user_workloads_secret = user_workloads_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user_workloads_secret] + + # 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 get_user_workloads_secret(self, + request: Optional[Union[environments.GetUserWorkloadsSecretRequest, 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]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Gets an existing user workloads Secret. Values of the "data" + field in the response are cleared. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_get_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.GetUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsSecretRequest, dict]): + The request object. Get user workloads Secret request. + name (str): + Required. The resource name of the + Secret to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" + + 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetUserWorkloadsSecretRequest): + request = environments.GetUserWorkloadsSecretRequest(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_user_workloads_secret] + + # 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_user_workloads_secrets(self, + request: Optional[Union[environments.ListUserWorkloadsSecretsRequest, 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.ListUserWorkloadsSecretsPager: + r"""Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_list_user_workloads_secrets(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.ListUserWorkloadsSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_secrets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest, dict]): + The request object. List user workloads Secrets request. + parent (str): + Required. List Secrets in the given + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsSecretsPager: + The user workloads Secrets for a + given environment. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListUserWorkloadsSecretsRequest): + request = environments.ListUserWorkloadsSecretsRequest(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_user_workloads_secrets] + + # 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.ListUserWorkloadsSecretsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_user_workloads_secret(self, + request: Optional[Union[environments.UpdateUserWorkloadsSecretRequest, dict]] = None, + *, + user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_update_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.UpdateUserWorkloadsSecretRequest( + ) + + # Make the request + response = client.update_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsSecretRequest, dict]): + The request object. Update user workloads Secret request. + user_workloads_secret (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret): + Optional. User workloads Secret to + override. + + This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [user_workloads_secret] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateUserWorkloadsSecretRequest): + request = environments.UpdateUserWorkloadsSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_workloads_secret is not None: + request.user_workloads_secret = user_workloads_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_user_workloads_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user_workloads_secret.name", request.user_workloads_secret.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_user_workloads_secret(self, + request: Optional[Union[environments.DeleteUserWorkloadsSecretRequest, 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]]] = (), + ) -> None: + r"""Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_delete_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.DeleteUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + client.delete_user_workloads_secret(request=request) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsSecretRequest, dict]): + The request object. Delete user workloads Secret request. + name (str): + Required. The Secret to delete, in + the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" + + 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`. + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteUserWorkloadsSecretRequest): + request = environments.DeleteUserWorkloadsSecretRequest(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_user_workloads_secret] + + # 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 create_user_workloads_config_map(self, + request: Optional[Union[environments.CreateUserWorkloadsConfigMapRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_create_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.CreateUserWorkloadsConfigMapRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsConfigMapRequest, dict]): + The request object. Create user workloads ConfigMap + request. + parent (str): + Required. The environment name to + create a ConfigMap for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_workloads_config_map (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap): + Required. User workloads ConfigMap to + create. + + This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [parent, user_workloads_config_map] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateUserWorkloadsConfigMapRequest): + request = environments.CreateUserWorkloadsConfigMapRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_workloads_config_map is not None: + request.user_workloads_config_map = user_workloads_config_map + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user_workloads_config_map] + + # 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 get_user_workloads_config_map(self, + request: Optional[Union[environments.GetUserWorkloadsConfigMapRequest, 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]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_get_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.GetUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsConfigMapRequest, dict]): + The request object. Get user workloads ConfigMap request. + name (str): + Required. The resource name of the + ConfigMap to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" + + 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetUserWorkloadsConfigMapRequest): + request = environments.GetUserWorkloadsConfigMapRequest(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_user_workloads_config_map] + + # 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_user_workloads_config_maps(self, + request: Optional[Union[environments.ListUserWorkloadsConfigMapsRequest, 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.ListUserWorkloadsConfigMapsPager: + r"""Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_list_user_workloads_config_maps(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.ListUserWorkloadsConfigMapsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_config_maps(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest, dict]): + The request object. List user workloads ConfigMaps + request. + parent (str): + Required. List ConfigMaps in the + given environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsConfigMapsPager: + The user workloads ConfigMaps for a + given environment. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListUserWorkloadsConfigMapsRequest): + request = environments.ListUserWorkloadsConfigMapsRequest(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_user_workloads_config_maps] + + # 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.ListUserWorkloadsConfigMapsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_user_workloads_config_map(self, + request: Optional[Union[environments.UpdateUserWorkloadsConfigMapRequest, dict]] = None, + *, + user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_update_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.UpdateUserWorkloadsConfigMapRequest( + ) + + # Make the request + response = client.update_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsConfigMapRequest, dict]): + The request object. Update user workloads ConfigMap + request. + user_workloads_config_map (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap): + Optional. User workloads ConfigMap to + override. + + This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [user_workloads_config_map] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateUserWorkloadsConfigMapRequest): + request = environments.UpdateUserWorkloadsConfigMapRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_workloads_config_map is not None: + request.user_workloads_config_map = user_workloads_config_map + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_user_workloads_config_map] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user_workloads_config_map.name", request.user_workloads_config_map.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_user_workloads_config_map(self, + request: Optional[Union[environments.DeleteUserWorkloadsConfigMapRequest, 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]]] = (), + ) -> None: + r"""Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1 + + def sample_delete_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.DeleteUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + client.delete_user_workloads_config_map(request=request) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsConfigMapRequest, dict]): + The request object. Delete user workloads ConfigMap + request. + name (str): + Required. The ConfigMap to delete, in + the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" + + 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`. + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteUserWorkloadsConfigMapRequest): + request = environments.DeleteUserWorkloadsConfigMapRequest(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_user_workloads_config_map] + + # 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 save_snapshot(self, + request: Optional[Union[environments.SaveSnapshotRequest, dict]] = 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 snapshots of a Cloud Composer environment. + + As a result of this operation, snapshot of environment's + state is stored in a location specified in the + SaveSnapshotRequest. + + .. 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.orchestration.airflow import service_v1 + + def sample_save_snapshot(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.SaveSnapshotRequest( + ) + + # Make the request + operation = client.save_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.SaveSnapshotRequest, dict]): + The request object. Request to create a snapshot of a + Cloud Composer environment. + retry (google.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.orchestration.airflow.service_v1.types.SaveSnapshotResponse` + Response to SaveSnapshotRequest. + + """ + # 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, environments.SaveSnapshotRequest): + request = environments.SaveSnapshotRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.save_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.SaveSnapshotResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def load_snapshot(self, + request: Optional[Union[environments.LoadSnapshotRequest, dict]] = 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"""Loads a snapshot of a Cloud Composer environment. + + As a result of this operation, a snapshot of + environment's specified in LoadSnapshotRequest is loaded + into the environment. + + .. 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.orchestration.airflow import service_v1 + + def sample_load_snapshot(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.LoadSnapshotRequest( + ) + + # Make the request + operation = client.load_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.LoadSnapshotRequest, dict]): + The request object. Request to load a snapshot into a + Cloud Composer environment. + retry (google.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.orchestration.airflow.service_v1.types.LoadSnapshotResponse` + Response to LoadSnapshotRequest. + + """ + # 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, environments.LoadSnapshotRequest): + request = environments.LoadSnapshotRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.load_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.LoadSnapshotResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def database_failover(self, + request: Optional[Union[environments.DatabaseFailoverRequest, dict]] = 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"""Triggers database failover (only for highly resilient + environments). + + .. 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.orchestration.airflow import service_v1 + + def sample_database_failover(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.DatabaseFailoverRequest( + ) + + # Make the request + operation = client.database_failover(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.DatabaseFailoverRequest, dict]): + The request object. Request to trigger database failover + (only for highly resilient + environments). + retry (google.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.orchestration.airflow.service_v1.types.DatabaseFailoverResponse` + Response for DatabaseFailoverRequest. + + """ + # 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, environments.DatabaseFailoverRequest): + request = environments.DatabaseFailoverRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.database_failover] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.DatabaseFailoverResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def fetch_database_properties(self, + request: Optional[Union[environments.FetchDatabasePropertiesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.FetchDatabasePropertiesResponse: + r"""Fetches database properties. + + .. 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.orchestration.airflow import service_v1 + + def sample_fetch_database_properties(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.FetchDatabasePropertiesRequest( + environment="environment_value", + ) + + # Make the request + response = client.fetch_database_properties(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesRequest, dict]): + The request object. Request to fetch properties of + environment's database. + retry (google.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.orchestration.airflow.service_v1.types.FetchDatabasePropertiesResponse: + Response for + FetchDatabasePropertiesRequest. + + """ + # 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, environments.FetchDatabasePropertiesRequest): + request = environments.FetchDatabasePropertiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_database_properties] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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) -> "EnvironmentsClient": + 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() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + 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() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + 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,) + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "EnvironmentsClient", +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py new file mode 100644 index 000000000000..0163c1f1931e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py @@ -0,0 +1,583 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1.types import environments + + +class ListEnvironmentsPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEnvironments`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse` + 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[..., environments.ListEnvironmentsResponse], + request: environments.ListEnvironmentsRequest, + response: environments.ListEnvironmentsResponse, + *, + 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.orchestration.airflow.service_v1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse): + 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 = environments.ListEnvironmentsRequest(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[environments.ListEnvironmentsResponse]: + 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[environments.Environment]: + for page in self.pages: + yield from page.environments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEnvironmentsAsyncPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEnvironments`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse` + 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[environments.ListEnvironmentsResponse]], + request: environments.ListEnvironmentsRequest, + response: environments.ListEnvironmentsResponse, + *, + 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.orchestration.airflow.service_v1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse): + 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 = environments.ListEnvironmentsRequest(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[environments.ListEnvironmentsResponse]: + 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[environments.Environment]: + async def async_generator(): + async for page in self.pages: + for response in page.environments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkloadsPager: + """A pager for iterating through ``list_workloads`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workloads`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkloads`` requests and continue to iterate + through the ``workloads`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse` + 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[..., environments.ListWorkloadsResponse], + request: environments.ListWorkloadsRequest, + response: environments.ListWorkloadsResponse, + *, + 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.orchestration.airflow.service_v1.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse): + 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 = environments.ListWorkloadsRequest(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[environments.ListWorkloadsResponse]: + 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[environments.ListWorkloadsResponse.ComposerWorkload]: + for page in self.pages: + yield from page.workloads + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkloadsAsyncPager: + """A pager for iterating through ``list_workloads`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workloads`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkloads`` requests and continue to iterate + through the ``workloads`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse` + 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[environments.ListWorkloadsResponse]], + request: environments.ListWorkloadsRequest, + response: environments.ListWorkloadsResponse, + *, + 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.orchestration.airflow.service_v1.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse): + 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 = environments.ListWorkloadsRequest(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[environments.ListWorkloadsResponse]: + 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[environments.ListWorkloadsResponse.ComposerWorkload]: + async def async_generator(): + async for page in self.pages: + for response in page.workloads: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUserWorkloadsSecretsPager: + """A pager for iterating through ``list_user_workloads_secrets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``user_workloads_secrets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUserWorkloadsSecrets`` requests and continue to iterate + through the ``user_workloads_secrets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse` + 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[..., environments.ListUserWorkloadsSecretsResponse], + request: environments.ListUserWorkloadsSecretsRequest, + response: environments.ListUserWorkloadsSecretsResponse, + *, + 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.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse): + 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 = environments.ListUserWorkloadsSecretsRequest(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[environments.ListUserWorkloadsSecretsResponse]: + 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[environments.UserWorkloadsSecret]: + for page in self.pages: + yield from page.user_workloads_secrets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUserWorkloadsSecretsAsyncPager: + """A pager for iterating through ``list_user_workloads_secrets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``user_workloads_secrets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUserWorkloadsSecrets`` requests and continue to iterate + through the ``user_workloads_secrets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse` + 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[environments.ListUserWorkloadsSecretsResponse]], + request: environments.ListUserWorkloadsSecretsRequest, + response: environments.ListUserWorkloadsSecretsResponse, + *, + 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.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse): + 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 = environments.ListUserWorkloadsSecretsRequest(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[environments.ListUserWorkloadsSecretsResponse]: + 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[environments.UserWorkloadsSecret]: + async def async_generator(): + async for page in self.pages: + for response in page.user_workloads_secrets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUserWorkloadsConfigMapsPager: + """A pager for iterating through ``list_user_workloads_config_maps`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``user_workloads_config_maps`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUserWorkloadsConfigMaps`` requests and continue to iterate + through the ``user_workloads_config_maps`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse` + 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[..., environments.ListUserWorkloadsConfigMapsResponse], + request: environments.ListUserWorkloadsConfigMapsRequest, + response: environments.ListUserWorkloadsConfigMapsResponse, + *, + 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.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse): + 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 = environments.ListUserWorkloadsConfigMapsRequest(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[environments.ListUserWorkloadsConfigMapsResponse]: + 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[environments.UserWorkloadsConfigMap]: + for page in self.pages: + yield from page.user_workloads_config_maps + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUserWorkloadsConfigMapsAsyncPager: + """A pager for iterating through ``list_user_workloads_config_maps`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``user_workloads_config_maps`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUserWorkloadsConfigMaps`` requests and continue to iterate + through the ``user_workloads_config_maps`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse` + 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[environments.ListUserWorkloadsConfigMapsResponse]], + request: environments.ListUserWorkloadsConfigMapsRequest, + response: environments.ListUserWorkloadsConfigMapsResponse, + *, + 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.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse): + 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 = environments.ListUserWorkloadsConfigMapsRequest(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[environments.ListUserWorkloadsConfigMapsResponse]: + 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[environments.UserWorkloadsConfigMap]: + async def async_generator(): + async for page in self.pages: + for response in page.user_workloads_config_maps: + 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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/README.rst new file mode 100644 index 000000000000..bce85d4987a6 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`EnvironmentsTransport` is the ABC for all transports. +- public child `EnvironmentsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `EnvironmentsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseEnvironmentsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `EnvironmentsRestTransport` 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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/__init__.py new file mode 100644 index 000000000000..0fb4434d4920 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/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 EnvironmentsTransport +from .grpc import EnvironmentsGrpcTransport +from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .rest import EnvironmentsRestTransport +from .rest import EnvironmentsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] +_transport_registry['grpc'] = EnvironmentsGrpcTransport +_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport +_transport_registry['rest'] = EnvironmentsRestTransport + +__all__ = ( + 'EnvironmentsTransport', + 'EnvironmentsGrpcTransport', + 'EnvironmentsGrpcAsyncIOTransport', + 'EnvironmentsRestTransport', + 'EnvironmentsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py new file mode 100644 index 000000000000..d0bdd6c78241 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py @@ -0,0 +1,526 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_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.orchestration.airflow.service_v1.types import environments +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class EnvironmentsTransport(abc.ABC): + """Abstract transport class for Environments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'composer.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: 'composer.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_environment: gapic_v1.method.wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.list_environments: gapic_v1.method.wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.execute_airflow_command: gapic_v1.method.wrap_method( + self.execute_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.stop_airflow_command: gapic_v1.method.wrap_method( + self.stop_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.poll_airflow_command: gapic_v1.method.wrap_method( + self.poll_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.list_workloads: gapic_v1.method.wrap_method( + self.list_workloads, + default_timeout=None, + client_info=client_info, + ), + self.check_upgrade: gapic_v1.method.wrap_method( + self.check_upgrade, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_secret: gapic_v1.method.wrap_method( + self.create_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_secret: gapic_v1.method.wrap_method( + self.get_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_secrets: gapic_v1.method.wrap_method( + self.list_user_workloads_secrets, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_secret: gapic_v1.method.wrap_method( + self.update_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_secret: gapic_v1.method.wrap_method( + self.delete_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_config_map: gapic_v1.method.wrap_method( + self.create_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_config_map: gapic_v1.method.wrap_method( + self.get_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_config_maps: gapic_v1.method.wrap_method( + self.list_user_workloads_config_maps, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_config_map: gapic_v1.method.wrap_method( + self.update_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_config_map: gapic_v1.method.wrap_method( + self.delete_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.save_snapshot: gapic_v1.method.wrap_method( + self.save_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.load_snapshot: gapic_v1.method.wrap_method( + self.load_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.database_failover: gapic_v1.method.wrap_method( + self.database_failover, + default_timeout=None, + client_info=client_info, + ), + self.fetch_database_properties: gapic_v1.method.wrap_method( + self.fetch_database_properties, + 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_environment(self) -> Callable[ + [environments.CreateEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_environment(self) -> Callable[ + [environments.GetEnvironmentRequest], + Union[ + environments.Environment, + Awaitable[environments.Environment] + ]]: + raise NotImplementedError() + + @property + def list_environments(self) -> Callable[ + [environments.ListEnvironmentsRequest], + Union[ + environments.ListEnvironmentsResponse, + Awaitable[environments.ListEnvironmentsResponse] + ]]: + raise NotImplementedError() + + @property + def update_environment(self) -> Callable[ + [environments.UpdateEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_environment(self) -> Callable[ + [environments.DeleteEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def execute_airflow_command(self) -> Callable[ + [environments.ExecuteAirflowCommandRequest], + Union[ + environments.ExecuteAirflowCommandResponse, + Awaitable[environments.ExecuteAirflowCommandResponse] + ]]: + raise NotImplementedError() + + @property + def stop_airflow_command(self) -> Callable[ + [environments.StopAirflowCommandRequest], + Union[ + environments.StopAirflowCommandResponse, + Awaitable[environments.StopAirflowCommandResponse] + ]]: + raise NotImplementedError() + + @property + def poll_airflow_command(self) -> Callable[ + [environments.PollAirflowCommandRequest], + Union[ + environments.PollAirflowCommandResponse, + Awaitable[environments.PollAirflowCommandResponse] + ]]: + raise NotImplementedError() + + @property + def list_workloads(self) -> Callable[ + [environments.ListWorkloadsRequest], + Union[ + environments.ListWorkloadsResponse, + Awaitable[environments.ListWorkloadsResponse] + ]]: + raise NotImplementedError() + + @property + def check_upgrade(self) -> Callable[ + [environments.CheckUpgradeRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def create_user_workloads_secret(self) -> Callable[ + [environments.CreateUserWorkloadsSecretRequest], + Union[ + environments.UserWorkloadsSecret, + Awaitable[environments.UserWorkloadsSecret] + ]]: + raise NotImplementedError() + + @property + def get_user_workloads_secret(self) -> Callable[ + [environments.GetUserWorkloadsSecretRequest], + Union[ + environments.UserWorkloadsSecret, + Awaitable[environments.UserWorkloadsSecret] + ]]: + raise NotImplementedError() + + @property + def list_user_workloads_secrets(self) -> Callable[ + [environments.ListUserWorkloadsSecretsRequest], + Union[ + environments.ListUserWorkloadsSecretsResponse, + Awaitable[environments.ListUserWorkloadsSecretsResponse] + ]]: + raise NotImplementedError() + + @property + def update_user_workloads_secret(self) -> Callable[ + [environments.UpdateUserWorkloadsSecretRequest], + Union[ + environments.UserWorkloadsSecret, + Awaitable[environments.UserWorkloadsSecret] + ]]: + raise NotImplementedError() + + @property + def delete_user_workloads_secret(self) -> Callable[ + [environments.DeleteUserWorkloadsSecretRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_user_workloads_config_map(self) -> Callable[ + [environments.CreateUserWorkloadsConfigMapRequest], + Union[ + environments.UserWorkloadsConfigMap, + Awaitable[environments.UserWorkloadsConfigMap] + ]]: + raise NotImplementedError() + + @property + def get_user_workloads_config_map(self) -> Callable[ + [environments.GetUserWorkloadsConfigMapRequest], + Union[ + environments.UserWorkloadsConfigMap, + Awaitable[environments.UserWorkloadsConfigMap] + ]]: + raise NotImplementedError() + + @property + def list_user_workloads_config_maps(self) -> Callable[ + [environments.ListUserWorkloadsConfigMapsRequest], + Union[ + environments.ListUserWorkloadsConfigMapsResponse, + Awaitable[environments.ListUserWorkloadsConfigMapsResponse] + ]]: + raise NotImplementedError() + + @property + def update_user_workloads_config_map(self) -> Callable[ + [environments.UpdateUserWorkloadsConfigMapRequest], + Union[ + environments.UserWorkloadsConfigMap, + Awaitable[environments.UserWorkloadsConfigMap] + ]]: + raise NotImplementedError() + + @property + def delete_user_workloads_config_map(self) -> Callable[ + [environments.DeleteUserWorkloadsConfigMapRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def save_snapshot(self) -> Callable[ + [environments.SaveSnapshotRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def load_snapshot(self) -> Callable[ + [environments.LoadSnapshotRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def database_failover(self) -> Callable[ + [environments.DatabaseFailoverRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def fetch_database_properties(self) -> Callable[ + [environments.FetchDatabasePropertiesRequest], + Union[ + environments.FetchDatabasePropertiesResponse, + Awaitable[environments.FetchDatabasePropertiesResponse] + ]]: + 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 delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'EnvironmentsTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py new file mode 100644 index 000000000000..59bf8374726a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py @@ -0,0 +1,1070 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1.types import environments +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, 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.orchestration.airflow.service.v1.Environments", + "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.orchestration.airflow.service.v1.Environments", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EnvironmentsGrpcTransport(EnvironmentsTransport): + """gRPC backend transport for Environments. + + Managed Apache Airflow Environments. + + 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 = 'composer.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: 'composer.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 = 'composer.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_environment(self) -> Callable[ + [environments.CreateEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the create environment method over gRPC. + + Create a new environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['create_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/CreateEnvironment', + request_serializer=environments.CreateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_environment'] + + @property + def get_environment(self) -> Callable[ + [environments.GetEnvironmentRequest], + environments.Environment]: + r"""Return a callable for the get environment method over gRPC. + + Get an existing environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['get_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/GetEnvironment', + request_serializer=environments.GetEnvironmentRequest.serialize, + response_deserializer=environments.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def list_environments(self) -> Callable[ + [environments.ListEnvironmentsRequest], + environments.ListEnvironmentsResponse]: + r"""Return a callable for the list environments method over gRPC. + + List environments. + + Returns: + Callable[[~.ListEnvironmentsRequest], + ~.ListEnvironmentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environments' not in self._stubs: + self._stubs['list_environments'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/ListEnvironments', + request_serializer=environments.ListEnvironmentsRequest.serialize, + response_deserializer=environments.ListEnvironmentsResponse.deserialize, + ) + return self._stubs['list_environments'] + + @property + def update_environment(self) -> Callable[ + [environments.UpdateEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the update environment method over gRPC. + + Update an environment. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['update_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateEnvironment', + request_serializer=environments.UpdateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environments.DeleteEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete environment method over gRPC. + + Delete an environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['delete_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteEnvironment', + request_serializer=environments.DeleteEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_environment'] + + @property + def execute_airflow_command(self) -> Callable[ + [environments.ExecuteAirflowCommandRequest], + environments.ExecuteAirflowCommandResponse]: + r"""Return a callable for the execute airflow command method over gRPC. + + Executes Airflow CLI command. + + Returns: + Callable[[~.ExecuteAirflowCommandRequest], + ~.ExecuteAirflowCommandResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'execute_airflow_command' not in self._stubs: + self._stubs['execute_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/ExecuteAirflowCommand', + request_serializer=environments.ExecuteAirflowCommandRequest.serialize, + response_deserializer=environments.ExecuteAirflowCommandResponse.deserialize, + ) + return self._stubs['execute_airflow_command'] + + @property + def stop_airflow_command(self) -> Callable[ + [environments.StopAirflowCommandRequest], + environments.StopAirflowCommandResponse]: + r"""Return a callable for the stop airflow command method over gRPC. + + Stops Airflow CLI command execution. + + Returns: + Callable[[~.StopAirflowCommandRequest], + ~.StopAirflowCommandResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_airflow_command' not in self._stubs: + self._stubs['stop_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/StopAirflowCommand', + request_serializer=environments.StopAirflowCommandRequest.serialize, + response_deserializer=environments.StopAirflowCommandResponse.deserialize, + ) + return self._stubs['stop_airflow_command'] + + @property + def poll_airflow_command(self) -> Callable[ + [environments.PollAirflowCommandRequest], + environments.PollAirflowCommandResponse]: + r"""Return a callable for the poll airflow command method over gRPC. + + Polls Airflow CLI command execution and fetches logs. + + Returns: + Callable[[~.PollAirflowCommandRequest], + ~.PollAirflowCommandResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'poll_airflow_command' not in self._stubs: + self._stubs['poll_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/PollAirflowCommand', + request_serializer=environments.PollAirflowCommandRequest.serialize, + response_deserializer=environments.PollAirflowCommandResponse.deserialize, + ) + return self._stubs['poll_airflow_command'] + + @property + def list_workloads(self) -> Callable[ + [environments.ListWorkloadsRequest], + environments.ListWorkloadsResponse]: + r"""Return a callable for the list workloads method over gRPC. + + Lists workloads in a Cloud Composer environment. Workload is a + unit that runs a single Composer component. + + This method is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + + Returns: + Callable[[~.ListWorkloadsRequest], + ~.ListWorkloadsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workloads' not in self._stubs: + self._stubs['list_workloads'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/ListWorkloads', + request_serializer=environments.ListWorkloadsRequest.serialize, + response_deserializer=environments.ListWorkloadsResponse.deserialize, + ) + return self._stubs['list_workloads'] + + @property + def check_upgrade(self) -> Callable[ + [environments.CheckUpgradeRequest], + operations_pb2.Operation]: + r"""Return a callable for the check upgrade method over gRPC. + + Check if an upgrade operation on the environment will + succeed. + In case of problems detailed info can be found in the + returned Operation. + + Returns: + Callable[[~.CheckUpgradeRequest], + ~.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 'check_upgrade' not in self._stubs: + self._stubs['check_upgrade'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/CheckUpgrade', + request_serializer=environments.CheckUpgradeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['check_upgrade'] + + @property + def create_user_workloads_secret(self) -> Callable[ + [environments.CreateUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + r"""Return a callable for the create user workloads secret method over gRPC. + + Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.CreateUserWorkloadsSecretRequest], + ~.UserWorkloadsSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['create_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/CreateUserWorkloadsSecret', + request_serializer=environments.CreateUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['create_user_workloads_secret'] + + @property + def get_user_workloads_secret(self) -> Callable[ + [environments.GetUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + r"""Return a callable for the get user workloads secret method over gRPC. + + Gets an existing user workloads Secret. Values of the "data" + field in the response are cleared. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.GetUserWorkloadsSecretRequest], + ~.UserWorkloadsSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['get_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/GetUserWorkloadsSecret', + request_serializer=environments.GetUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['get_user_workloads_secret'] + + @property + def list_user_workloads_secrets(self) -> Callable[ + [environments.ListUserWorkloadsSecretsRequest], + environments.ListUserWorkloadsSecretsResponse]: + r"""Return a callable for the list user workloads secrets method over gRPC. + + Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.ListUserWorkloadsSecretsRequest], + ~.ListUserWorkloadsSecretsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secrets' not in self._stubs: + self._stubs['list_user_workloads_secrets'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/ListUserWorkloadsSecrets', + request_serializer=environments.ListUserWorkloadsSecretsRequest.serialize, + response_deserializer=environments.ListUserWorkloadsSecretsResponse.deserialize, + ) + return self._stubs['list_user_workloads_secrets'] + + @property + def update_user_workloads_secret(self) -> Callable[ + [environments.UpdateUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + r"""Return a callable for the update user workloads secret method over gRPC. + + Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.UpdateUserWorkloadsSecretRequest], + ~.UserWorkloadsSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['update_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateUserWorkloadsSecret', + request_serializer=environments.UpdateUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['update_user_workloads_secret'] + + @property + def delete_user_workloads_secret(self) -> Callable[ + [environments.DeleteUserWorkloadsSecretRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete user workloads secret method over gRPC. + + Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.DeleteUserWorkloadsSecretRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['delete_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteUserWorkloadsSecret', + request_serializer=environments.DeleteUserWorkloadsSecretRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user_workloads_secret'] + + @property + def create_user_workloads_config_map(self) -> Callable[ + [environments.CreateUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + r"""Return a callable for the create user workloads config + map method over gRPC. + + Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.CreateUserWorkloadsConfigMapRequest], + ~.UserWorkloadsConfigMap]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['create_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/CreateUserWorkloadsConfigMap', + request_serializer=environments.CreateUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['create_user_workloads_config_map'] + + @property + def get_user_workloads_config_map(self) -> Callable[ + [environments.GetUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + r"""Return a callable for the get user workloads config map method over gRPC. + + Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.GetUserWorkloadsConfigMapRequest], + ~.UserWorkloadsConfigMap]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['get_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/GetUserWorkloadsConfigMap', + request_serializer=environments.GetUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['get_user_workloads_config_map'] + + @property + def list_user_workloads_config_maps(self) -> Callable[ + [environments.ListUserWorkloadsConfigMapsRequest], + environments.ListUserWorkloadsConfigMapsResponse]: + r"""Return a callable for the list user workloads config + maps method over gRPC. + + Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.ListUserWorkloadsConfigMapsRequest], + ~.ListUserWorkloadsConfigMapsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_maps' not in self._stubs: + self._stubs['list_user_workloads_config_maps'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/ListUserWorkloadsConfigMaps', + request_serializer=environments.ListUserWorkloadsConfigMapsRequest.serialize, + response_deserializer=environments.ListUserWorkloadsConfigMapsResponse.deserialize, + ) + return self._stubs['list_user_workloads_config_maps'] + + @property + def update_user_workloads_config_map(self) -> Callable[ + [environments.UpdateUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + r"""Return a callable for the update user workloads config + map method over gRPC. + + Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.UpdateUserWorkloadsConfigMapRequest], + ~.UserWorkloadsConfigMap]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['update_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateUserWorkloadsConfigMap', + request_serializer=environments.UpdateUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['update_user_workloads_config_map'] + + @property + def delete_user_workloads_config_map(self) -> Callable[ + [environments.DeleteUserWorkloadsConfigMapRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete user workloads config + map method over gRPC. + + Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.DeleteUserWorkloadsConfigMapRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['delete_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteUserWorkloadsConfigMap', + request_serializer=environments.DeleteUserWorkloadsConfigMapRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user_workloads_config_map'] + + @property + def save_snapshot(self) -> Callable[ + [environments.SaveSnapshotRequest], + operations_pb2.Operation]: + r"""Return a callable for the save snapshot method over gRPC. + + Creates a snapshots of a Cloud Composer environment. + + As a result of this operation, snapshot of environment's + state is stored in a location specified in the + SaveSnapshotRequest. + + Returns: + Callable[[~.SaveSnapshotRequest], + ~.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 'save_snapshot' not in self._stubs: + self._stubs['save_snapshot'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/SaveSnapshot', + request_serializer=environments.SaveSnapshotRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['save_snapshot'] + + @property + def load_snapshot(self) -> Callable[ + [environments.LoadSnapshotRequest], + operations_pb2.Operation]: + r"""Return a callable for the load snapshot method over gRPC. + + Loads a snapshot of a Cloud Composer environment. + + As a result of this operation, a snapshot of + environment's specified in LoadSnapshotRequest is loaded + into the environment. + + Returns: + Callable[[~.LoadSnapshotRequest], + ~.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 'load_snapshot' not in self._stubs: + self._stubs['load_snapshot'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/LoadSnapshot', + request_serializer=environments.LoadSnapshotRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['load_snapshot'] + + @property + def database_failover(self) -> Callable[ + [environments.DatabaseFailoverRequest], + operations_pb2.Operation]: + r"""Return a callable for the database failover method over gRPC. + + Triggers database failover (only for highly resilient + environments). + + Returns: + Callable[[~.DatabaseFailoverRequest], + ~.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 'database_failover' not in self._stubs: + self._stubs['database_failover'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/DatabaseFailover', + request_serializer=environments.DatabaseFailoverRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['database_failover'] + + @property + def fetch_database_properties(self) -> Callable[ + [environments.FetchDatabasePropertiesRequest], + environments.FetchDatabasePropertiesResponse]: + r"""Return a callable for the fetch database properties method over gRPC. + + Fetches database properties. + + Returns: + Callable[[~.FetchDatabasePropertiesRequest], + ~.FetchDatabasePropertiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fetch_database_properties' not in self._stubs: + self._stubs['fetch_database_properties'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/FetchDatabaseProperties', + request_serializer=environments.FetchDatabasePropertiesRequest.serialize, + response_deserializer=environments.FetchDatabasePropertiesResponse.deserialize, + ) + return self._stubs['fetch_database_properties'] + + 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 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__ = ( + 'EnvironmentsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py new file mode 100644 index 000000000000..78698a3ca9b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py @@ -0,0 +1,1220 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1.types import environments +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import EnvironmentsGrpcTransport + +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.orchestration.airflow.service.v1.Environments", + "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.orchestration.airflow.service.v1.Environments", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): + """gRPC AsyncIO backend transport for Environments. + + Managed Apache Airflow Environments. + + 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 = 'composer.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 = 'composer.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: 'composer.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_environment(self) -> Callable[ + [environments.CreateEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create environment method over gRPC. + + Create a new environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['create_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/CreateEnvironment', + request_serializer=environments.CreateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_environment'] + + @property + def get_environment(self) -> Callable[ + [environments.GetEnvironmentRequest], + Awaitable[environments.Environment]]: + r"""Return a callable for the get environment method over gRPC. + + Get an existing environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['get_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/GetEnvironment', + request_serializer=environments.GetEnvironmentRequest.serialize, + response_deserializer=environments.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def list_environments(self) -> Callable[ + [environments.ListEnvironmentsRequest], + Awaitable[environments.ListEnvironmentsResponse]]: + r"""Return a callable for the list environments method over gRPC. + + List environments. + + Returns: + Callable[[~.ListEnvironmentsRequest], + Awaitable[~.ListEnvironmentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environments' not in self._stubs: + self._stubs['list_environments'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/ListEnvironments', + request_serializer=environments.ListEnvironmentsRequest.serialize, + response_deserializer=environments.ListEnvironmentsResponse.deserialize, + ) + return self._stubs['list_environments'] + + @property + def update_environment(self) -> Callable[ + [environments.UpdateEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update environment method over gRPC. + + Update an environment. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['update_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateEnvironment', + request_serializer=environments.UpdateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environments.DeleteEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete environment method over gRPC. + + Delete an environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['delete_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteEnvironment', + request_serializer=environments.DeleteEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_environment'] + + @property + def execute_airflow_command(self) -> Callable[ + [environments.ExecuteAirflowCommandRequest], + Awaitable[environments.ExecuteAirflowCommandResponse]]: + r"""Return a callable for the execute airflow command method over gRPC. + + Executes Airflow CLI command. + + Returns: + Callable[[~.ExecuteAirflowCommandRequest], + Awaitable[~.ExecuteAirflowCommandResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'execute_airflow_command' not in self._stubs: + self._stubs['execute_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/ExecuteAirflowCommand', + request_serializer=environments.ExecuteAirflowCommandRequest.serialize, + response_deserializer=environments.ExecuteAirflowCommandResponse.deserialize, + ) + return self._stubs['execute_airflow_command'] + + @property + def stop_airflow_command(self) -> Callable[ + [environments.StopAirflowCommandRequest], + Awaitable[environments.StopAirflowCommandResponse]]: + r"""Return a callable for the stop airflow command method over gRPC. + + Stops Airflow CLI command execution. + + Returns: + Callable[[~.StopAirflowCommandRequest], + Awaitable[~.StopAirflowCommandResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_airflow_command' not in self._stubs: + self._stubs['stop_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/StopAirflowCommand', + request_serializer=environments.StopAirflowCommandRequest.serialize, + response_deserializer=environments.StopAirflowCommandResponse.deserialize, + ) + return self._stubs['stop_airflow_command'] + + @property + def poll_airflow_command(self) -> Callable[ + [environments.PollAirflowCommandRequest], + Awaitable[environments.PollAirflowCommandResponse]]: + r"""Return a callable for the poll airflow command method over gRPC. + + Polls Airflow CLI command execution and fetches logs. + + Returns: + Callable[[~.PollAirflowCommandRequest], + Awaitable[~.PollAirflowCommandResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'poll_airflow_command' not in self._stubs: + self._stubs['poll_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/PollAirflowCommand', + request_serializer=environments.PollAirflowCommandRequest.serialize, + response_deserializer=environments.PollAirflowCommandResponse.deserialize, + ) + return self._stubs['poll_airflow_command'] + + @property + def list_workloads(self) -> Callable[ + [environments.ListWorkloadsRequest], + Awaitable[environments.ListWorkloadsResponse]]: + r"""Return a callable for the list workloads method over gRPC. + + Lists workloads in a Cloud Composer environment. Workload is a + unit that runs a single Composer component. + + This method is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + + Returns: + Callable[[~.ListWorkloadsRequest], + Awaitable[~.ListWorkloadsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workloads' not in self._stubs: + self._stubs['list_workloads'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/ListWorkloads', + request_serializer=environments.ListWorkloadsRequest.serialize, + response_deserializer=environments.ListWorkloadsResponse.deserialize, + ) + return self._stubs['list_workloads'] + + @property + def check_upgrade(self) -> Callable[ + [environments.CheckUpgradeRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the check upgrade method over gRPC. + + Check if an upgrade operation on the environment will + succeed. + In case of problems detailed info can be found in the + returned Operation. + + Returns: + Callable[[~.CheckUpgradeRequest], + 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 'check_upgrade' not in self._stubs: + self._stubs['check_upgrade'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/CheckUpgrade', + request_serializer=environments.CheckUpgradeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['check_upgrade'] + + @property + def create_user_workloads_secret(self) -> Callable[ + [environments.CreateUserWorkloadsSecretRequest], + Awaitable[environments.UserWorkloadsSecret]]: + r"""Return a callable for the create user workloads secret method over gRPC. + + Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.CreateUserWorkloadsSecretRequest], + Awaitable[~.UserWorkloadsSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['create_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/CreateUserWorkloadsSecret', + request_serializer=environments.CreateUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['create_user_workloads_secret'] + + @property + def get_user_workloads_secret(self) -> Callable[ + [environments.GetUserWorkloadsSecretRequest], + Awaitable[environments.UserWorkloadsSecret]]: + r"""Return a callable for the get user workloads secret method over gRPC. + + Gets an existing user workloads Secret. Values of the "data" + field in the response are cleared. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.GetUserWorkloadsSecretRequest], + Awaitable[~.UserWorkloadsSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['get_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/GetUserWorkloadsSecret', + request_serializer=environments.GetUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['get_user_workloads_secret'] + + @property + def list_user_workloads_secrets(self) -> Callable[ + [environments.ListUserWorkloadsSecretsRequest], + Awaitable[environments.ListUserWorkloadsSecretsResponse]]: + r"""Return a callable for the list user workloads secrets method over gRPC. + + Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.ListUserWorkloadsSecretsRequest], + Awaitable[~.ListUserWorkloadsSecretsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secrets' not in self._stubs: + self._stubs['list_user_workloads_secrets'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/ListUserWorkloadsSecrets', + request_serializer=environments.ListUserWorkloadsSecretsRequest.serialize, + response_deserializer=environments.ListUserWorkloadsSecretsResponse.deserialize, + ) + return self._stubs['list_user_workloads_secrets'] + + @property + def update_user_workloads_secret(self) -> Callable[ + [environments.UpdateUserWorkloadsSecretRequest], + Awaitable[environments.UserWorkloadsSecret]]: + r"""Return a callable for the update user workloads secret method over gRPC. + + Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.UpdateUserWorkloadsSecretRequest], + Awaitable[~.UserWorkloadsSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['update_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateUserWorkloadsSecret', + request_serializer=environments.UpdateUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['update_user_workloads_secret'] + + @property + def delete_user_workloads_secret(self) -> Callable[ + [environments.DeleteUserWorkloadsSecretRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete user workloads secret method over gRPC. + + Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.DeleteUserWorkloadsSecretRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['delete_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteUserWorkloadsSecret', + request_serializer=environments.DeleteUserWorkloadsSecretRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user_workloads_secret'] + + @property + def create_user_workloads_config_map(self) -> Callable[ + [environments.CreateUserWorkloadsConfigMapRequest], + Awaitable[environments.UserWorkloadsConfigMap]]: + r"""Return a callable for the create user workloads config + map method over gRPC. + + Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.CreateUserWorkloadsConfigMapRequest], + Awaitable[~.UserWorkloadsConfigMap]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['create_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/CreateUserWorkloadsConfigMap', + request_serializer=environments.CreateUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['create_user_workloads_config_map'] + + @property + def get_user_workloads_config_map(self) -> Callable[ + [environments.GetUserWorkloadsConfigMapRequest], + Awaitable[environments.UserWorkloadsConfigMap]]: + r"""Return a callable for the get user workloads config map method over gRPC. + + Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.GetUserWorkloadsConfigMapRequest], + Awaitable[~.UserWorkloadsConfigMap]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['get_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/GetUserWorkloadsConfigMap', + request_serializer=environments.GetUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['get_user_workloads_config_map'] + + @property + def list_user_workloads_config_maps(self) -> Callable[ + [environments.ListUserWorkloadsConfigMapsRequest], + Awaitable[environments.ListUserWorkloadsConfigMapsResponse]]: + r"""Return a callable for the list user workloads config + maps method over gRPC. + + Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.ListUserWorkloadsConfigMapsRequest], + Awaitable[~.ListUserWorkloadsConfigMapsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_maps' not in self._stubs: + self._stubs['list_user_workloads_config_maps'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/ListUserWorkloadsConfigMaps', + request_serializer=environments.ListUserWorkloadsConfigMapsRequest.serialize, + response_deserializer=environments.ListUserWorkloadsConfigMapsResponse.deserialize, + ) + return self._stubs['list_user_workloads_config_maps'] + + @property + def update_user_workloads_config_map(self) -> Callable[ + [environments.UpdateUserWorkloadsConfigMapRequest], + Awaitable[environments.UserWorkloadsConfigMap]]: + r"""Return a callable for the update user workloads config + map method over gRPC. + + Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.UpdateUserWorkloadsConfigMapRequest], + Awaitable[~.UserWorkloadsConfigMap]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['update_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateUserWorkloadsConfigMap', + request_serializer=environments.UpdateUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['update_user_workloads_config_map'] + + @property + def delete_user_workloads_config_map(self) -> Callable[ + [environments.DeleteUserWorkloadsConfigMapRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete user workloads config + map method over gRPC. + + Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.DeleteUserWorkloadsConfigMapRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['delete_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteUserWorkloadsConfigMap', + request_serializer=environments.DeleteUserWorkloadsConfigMapRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user_workloads_config_map'] + + @property + def save_snapshot(self) -> Callable[ + [environments.SaveSnapshotRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the save snapshot method over gRPC. + + Creates a snapshots of a Cloud Composer environment. + + As a result of this operation, snapshot of environment's + state is stored in a location specified in the + SaveSnapshotRequest. + + Returns: + Callable[[~.SaveSnapshotRequest], + 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 'save_snapshot' not in self._stubs: + self._stubs['save_snapshot'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/SaveSnapshot', + request_serializer=environments.SaveSnapshotRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['save_snapshot'] + + @property + def load_snapshot(self) -> Callable[ + [environments.LoadSnapshotRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the load snapshot method over gRPC. + + Loads a snapshot of a Cloud Composer environment. + + As a result of this operation, a snapshot of + environment's specified in LoadSnapshotRequest is loaded + into the environment. + + Returns: + Callable[[~.LoadSnapshotRequest], + 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 'load_snapshot' not in self._stubs: + self._stubs['load_snapshot'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/LoadSnapshot', + request_serializer=environments.LoadSnapshotRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['load_snapshot'] + + @property + def database_failover(self) -> Callable[ + [environments.DatabaseFailoverRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the database failover method over gRPC. + + Triggers database failover (only for highly resilient + environments). + + Returns: + Callable[[~.DatabaseFailoverRequest], + 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 'database_failover' not in self._stubs: + self._stubs['database_failover'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/DatabaseFailover', + request_serializer=environments.DatabaseFailoverRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['database_failover'] + + @property + def fetch_database_properties(self) -> Callable[ + [environments.FetchDatabasePropertiesRequest], + Awaitable[environments.FetchDatabasePropertiesResponse]]: + r"""Return a callable for the fetch database properties method over gRPC. + + Fetches database properties. + + Returns: + Callable[[~.FetchDatabasePropertiesRequest], + Awaitable[~.FetchDatabasePropertiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fetch_database_properties' not in self._stubs: + self._stubs['fetch_database_properties'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.Environments/FetchDatabaseProperties', + request_serializer=environments.FetchDatabasePropertiesRequest.serialize, + response_deserializer=environments.FetchDatabasePropertiesResponse.deserialize, + ) + return self._stubs['fetch_database_properties'] + + 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_environment: self._wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: self._wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.list_environments: self._wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: self._wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: self._wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.execute_airflow_command: self._wrap_method( + self.execute_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.stop_airflow_command: self._wrap_method( + self.stop_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.poll_airflow_command: self._wrap_method( + self.poll_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.list_workloads: self._wrap_method( + self.list_workloads, + default_timeout=None, + client_info=client_info, + ), + self.check_upgrade: self._wrap_method( + self.check_upgrade, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_secret: self._wrap_method( + self.create_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_secret: self._wrap_method( + self.get_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_secrets: self._wrap_method( + self.list_user_workloads_secrets, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_secret: self._wrap_method( + self.update_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_secret: self._wrap_method( + self.delete_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_config_map: self._wrap_method( + self.create_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_config_map: self._wrap_method( + self.get_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_config_maps: self._wrap_method( + self.list_user_workloads_config_maps, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_config_map: self._wrap_method( + self.update_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_config_map: self._wrap_method( + self.delete_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.save_snapshot: self._wrap_method( + self.save_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.load_snapshot: self._wrap_method( + self.load_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.database_failover: self._wrap_method( + self.database_failover, + default_timeout=None, + client_info=client_info, + ), + self.fetch_database_properties: self._wrap_method( + self.fetch_database_properties, + 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 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__ = ( + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py new file mode 100644 index 000000000000..53477005f41e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py @@ -0,0 +1,4687 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1.types import environments +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseEnvironmentsRestTransport +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 EnvironmentsRestInterceptor: + """Interceptor for Environments. + + 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 EnvironmentsRestTransport. + + .. code-block:: python + class MyCustomEnvironmentsInterceptor(EnvironmentsRestInterceptor): + def pre_check_upgrade(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_check_upgrade(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_environment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_environment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_user_workloads_config_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user_workloads_config_map(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_user_workloads_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user_workloads_secret(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_database_failover(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_database_failover(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_environment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_environment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_user_workloads_config_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_user_workloads_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_execute_airflow_command(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_execute_airflow_command(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_database_properties(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_database_properties(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_environment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_environment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_user_workloads_config_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user_workloads_config_map(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_user_workloads_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user_workloads_secret(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_environments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_environments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_user_workloads_config_maps(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_user_workloads_config_maps(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_user_workloads_secrets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_user_workloads_secrets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workloads(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workloads(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_load_snapshot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_load_snapshot(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_poll_airflow_command(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_poll_airflow_command(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_save_snapshot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_save_snapshot(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_airflow_command(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_airflow_command(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_environment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_environment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user_workloads_config_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user_workloads_config_map(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user_workloads_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user_workloads_secret(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EnvironmentsRestTransport(interceptor=MyCustomEnvironmentsInterceptor()) + client = EnvironmentsClient(transport=transport) + + + """ + def pre_check_upgrade(self, request: environments.CheckUpgradeRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CheckUpgradeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for check_upgrade + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_check_upgrade(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for check_upgrade + + DEPRECATED. Please use the `post_check_upgrade_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_check_upgrade` interceptor runs + before the `post_check_upgrade_with_metadata` interceptor. + """ + return response + + def post_check_upgrade_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for check_upgrade + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_check_upgrade_with_metadata` + interceptor in new development instead of the `post_check_upgrade` interceptor. + When both interceptors are used, this `post_check_upgrade_with_metadata` interceptor runs after the + `post_check_upgrade` interceptor. The (possibly modified) response returned by + `post_check_upgrade` will be passed to + `post_check_upgrade_with_metadata`. + """ + return response, metadata + + def pre_create_environment(self, request: environments.CreateEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_environment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_create_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_environment + + DEPRECATED. Please use the `post_create_environment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_create_environment` interceptor runs + before the `post_create_environment_with_metadata` interceptor. + """ + return response + + def post_create_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_environment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_create_environment_with_metadata` + interceptor in new development instead of the `post_create_environment` interceptor. + When both interceptors are used, this `post_create_environment_with_metadata` interceptor runs after the + `post_create_environment` interceptor. The (possibly modified) response returned by + `post_create_environment` will be passed to + `post_create_environment_with_metadata`. + """ + return response, metadata + + def pre_create_user_workloads_config_map(self, request: environments.CreateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_user_workloads_config_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_create_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: + """Post-rpc interceptor for create_user_workloads_config_map + + DEPRECATED. Please use the `post_create_user_workloads_config_map_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_create_user_workloads_config_map` interceptor runs + before the `post_create_user_workloads_config_map_with_metadata` interceptor. + """ + return response + + def post_create_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_user_workloads_config_map + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_create_user_workloads_config_map_with_metadata` + interceptor in new development instead of the `post_create_user_workloads_config_map` interceptor. + When both interceptors are used, this `post_create_user_workloads_config_map_with_metadata` interceptor runs after the + `post_create_user_workloads_config_map` interceptor. The (possibly modified) response returned by + `post_create_user_workloads_config_map` will be passed to + `post_create_user_workloads_config_map_with_metadata`. + """ + return response, metadata + + def pre_create_user_workloads_secret(self, request: environments.CreateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_user_workloads_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_create_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: + """Post-rpc interceptor for create_user_workloads_secret + + DEPRECATED. Please use the `post_create_user_workloads_secret_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_create_user_workloads_secret` interceptor runs + before the `post_create_user_workloads_secret_with_metadata` interceptor. + """ + return response + + def post_create_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_user_workloads_secret + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_create_user_workloads_secret_with_metadata` + interceptor in new development instead of the `post_create_user_workloads_secret` interceptor. + When both interceptors are used, this `post_create_user_workloads_secret_with_metadata` interceptor runs after the + `post_create_user_workloads_secret` interceptor. The (possibly modified) response returned by + `post_create_user_workloads_secret` will be passed to + `post_create_user_workloads_secret_with_metadata`. + """ + return response, metadata + + def pre_database_failover(self, request: environments.DatabaseFailoverRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DatabaseFailoverRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for database_failover + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_database_failover(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for database_failover + + DEPRECATED. Please use the `post_database_failover_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_database_failover` interceptor runs + before the `post_database_failover_with_metadata` interceptor. + """ + return response + + def post_database_failover_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for database_failover + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_database_failover_with_metadata` + interceptor in new development instead of the `post_database_failover` interceptor. + When both interceptors are used, this `post_database_failover_with_metadata` interceptor runs after the + `post_database_failover` interceptor. The (possibly modified) response returned by + `post_database_failover` will be passed to + `post_database_failover_with_metadata`. + """ + return response, metadata + + def pre_delete_environment(self, request: environments.DeleteEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_environment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_delete_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_environment + + DEPRECATED. Please use the `post_delete_environment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_delete_environment` interceptor runs + before the `post_delete_environment_with_metadata` interceptor. + """ + return response + + def post_delete_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_environment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_delete_environment_with_metadata` + interceptor in new development instead of the `post_delete_environment` interceptor. + When both interceptors are used, this `post_delete_environment_with_metadata` interceptor runs after the + `post_delete_environment` interceptor. The (possibly modified) response returned by + `post_delete_environment` will be passed to + `post_delete_environment_with_metadata`. + """ + return response, metadata + + def pre_delete_user_workloads_config_map(self, request: environments.DeleteUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_user_workloads_config_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def pre_delete_user_workloads_secret(self, request: environments.DeleteUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_user_workloads_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def pre_execute_airflow_command(self, request: environments.ExecuteAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ExecuteAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for execute_airflow_command + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_execute_airflow_command(self, response: environments.ExecuteAirflowCommandResponse) -> environments.ExecuteAirflowCommandResponse: + """Post-rpc interceptor for execute_airflow_command + + DEPRECATED. Please use the `post_execute_airflow_command_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_execute_airflow_command` interceptor runs + before the `post_execute_airflow_command_with_metadata` interceptor. + """ + return response + + def post_execute_airflow_command_with_metadata(self, response: environments.ExecuteAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ExecuteAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for execute_airflow_command + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_execute_airflow_command_with_metadata` + interceptor in new development instead of the `post_execute_airflow_command` interceptor. + When both interceptors are used, this `post_execute_airflow_command_with_metadata` interceptor runs after the + `post_execute_airflow_command` interceptor. The (possibly modified) response returned by + `post_execute_airflow_command` will be passed to + `post_execute_airflow_command_with_metadata`. + """ + return response, metadata + + def pre_fetch_database_properties(self, request: environments.FetchDatabasePropertiesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.FetchDatabasePropertiesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for fetch_database_properties + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_fetch_database_properties(self, response: environments.FetchDatabasePropertiesResponse) -> environments.FetchDatabasePropertiesResponse: + """Post-rpc interceptor for fetch_database_properties + + DEPRECATED. Please use the `post_fetch_database_properties_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_fetch_database_properties` interceptor runs + before the `post_fetch_database_properties_with_metadata` interceptor. + """ + return response + + def post_fetch_database_properties_with_metadata(self, response: environments.FetchDatabasePropertiesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.FetchDatabasePropertiesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for fetch_database_properties + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_fetch_database_properties_with_metadata` + interceptor in new development instead of the `post_fetch_database_properties` interceptor. + When both interceptors are used, this `post_fetch_database_properties_with_metadata` interceptor runs after the + `post_fetch_database_properties` interceptor. The (possibly modified) response returned by + `post_fetch_database_properties` will be passed to + `post_fetch_database_properties_with_metadata`. + """ + return response, metadata + + def pre_get_environment(self, request: environments.GetEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_environment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_get_environment(self, response: environments.Environment) -> environments.Environment: + """Post-rpc interceptor for get_environment + + DEPRECATED. Please use the `post_get_environment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_get_environment` interceptor runs + before the `post_get_environment_with_metadata` interceptor. + """ + return response + + def post_get_environment_with_metadata(self, response: environments.Environment, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.Environment, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_environment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_get_environment_with_metadata` + interceptor in new development instead of the `post_get_environment` interceptor. + When both interceptors are used, this `post_get_environment_with_metadata` interceptor runs after the + `post_get_environment` interceptor. The (possibly modified) response returned by + `post_get_environment` will be passed to + `post_get_environment_with_metadata`. + """ + return response, metadata + + def pre_get_user_workloads_config_map(self, request: environments.GetUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_user_workloads_config_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_get_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: + """Post-rpc interceptor for get_user_workloads_config_map + + DEPRECATED. Please use the `post_get_user_workloads_config_map_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_get_user_workloads_config_map` interceptor runs + before the `post_get_user_workloads_config_map_with_metadata` interceptor. + """ + return response + + def post_get_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_user_workloads_config_map + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_get_user_workloads_config_map_with_metadata` + interceptor in new development instead of the `post_get_user_workloads_config_map` interceptor. + When both interceptors are used, this `post_get_user_workloads_config_map_with_metadata` interceptor runs after the + `post_get_user_workloads_config_map` interceptor. The (possibly modified) response returned by + `post_get_user_workloads_config_map` will be passed to + `post_get_user_workloads_config_map_with_metadata`. + """ + return response, metadata + + def pre_get_user_workloads_secret(self, request: environments.GetUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_user_workloads_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_get_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: + """Post-rpc interceptor for get_user_workloads_secret + + DEPRECATED. Please use the `post_get_user_workloads_secret_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_get_user_workloads_secret` interceptor runs + before the `post_get_user_workloads_secret_with_metadata` interceptor. + """ + return response + + def post_get_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_user_workloads_secret + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_get_user_workloads_secret_with_metadata` + interceptor in new development instead of the `post_get_user_workloads_secret` interceptor. + When both interceptors are used, this `post_get_user_workloads_secret_with_metadata` interceptor runs after the + `post_get_user_workloads_secret` interceptor. The (possibly modified) response returned by + `post_get_user_workloads_secret` will be passed to + `post_get_user_workloads_secret_with_metadata`. + """ + return response, metadata + + def pre_list_environments(self, request: environments.ListEnvironmentsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListEnvironmentsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_environments + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_list_environments(self, response: environments.ListEnvironmentsResponse) -> environments.ListEnvironmentsResponse: + """Post-rpc interceptor for list_environments + + DEPRECATED. Please use the `post_list_environments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_list_environments` interceptor runs + before the `post_list_environments_with_metadata` interceptor. + """ + return response + + def post_list_environments_with_metadata(self, response: environments.ListEnvironmentsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListEnvironmentsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_environments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_list_environments_with_metadata` + interceptor in new development instead of the `post_list_environments` interceptor. + When both interceptors are used, this `post_list_environments_with_metadata` interceptor runs after the + `post_list_environments` interceptor. The (possibly modified) response returned by + `post_list_environments` will be passed to + `post_list_environments_with_metadata`. + """ + return response, metadata + + def pre_list_user_workloads_config_maps(self, request: environments.ListUserWorkloadsConfigMapsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsConfigMapsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_user_workloads_config_maps + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_list_user_workloads_config_maps(self, response: environments.ListUserWorkloadsConfigMapsResponse) -> environments.ListUserWorkloadsConfigMapsResponse: + """Post-rpc interceptor for list_user_workloads_config_maps + + DEPRECATED. Please use the `post_list_user_workloads_config_maps_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_list_user_workloads_config_maps` interceptor runs + before the `post_list_user_workloads_config_maps_with_metadata` interceptor. + """ + return response + + def post_list_user_workloads_config_maps_with_metadata(self, response: environments.ListUserWorkloadsConfigMapsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsConfigMapsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_user_workloads_config_maps + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_list_user_workloads_config_maps_with_metadata` + interceptor in new development instead of the `post_list_user_workloads_config_maps` interceptor. + When both interceptors are used, this `post_list_user_workloads_config_maps_with_metadata` interceptor runs after the + `post_list_user_workloads_config_maps` interceptor. The (possibly modified) response returned by + `post_list_user_workloads_config_maps` will be passed to + `post_list_user_workloads_config_maps_with_metadata`. + """ + return response, metadata + + def pre_list_user_workloads_secrets(self, request: environments.ListUserWorkloadsSecretsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsSecretsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_user_workloads_secrets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_list_user_workloads_secrets(self, response: environments.ListUserWorkloadsSecretsResponse) -> environments.ListUserWorkloadsSecretsResponse: + """Post-rpc interceptor for list_user_workloads_secrets + + DEPRECATED. Please use the `post_list_user_workloads_secrets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_list_user_workloads_secrets` interceptor runs + before the `post_list_user_workloads_secrets_with_metadata` interceptor. + """ + return response + + def post_list_user_workloads_secrets_with_metadata(self, response: environments.ListUserWorkloadsSecretsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsSecretsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_user_workloads_secrets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_list_user_workloads_secrets_with_metadata` + interceptor in new development instead of the `post_list_user_workloads_secrets` interceptor. + When both interceptors are used, this `post_list_user_workloads_secrets_with_metadata` interceptor runs after the + `post_list_user_workloads_secrets` interceptor. The (possibly modified) response returned by + `post_list_user_workloads_secrets` will be passed to + `post_list_user_workloads_secrets_with_metadata`. + """ + return response, metadata + + def pre_list_workloads(self, request: environments.ListWorkloadsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListWorkloadsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_workloads + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_list_workloads(self, response: environments.ListWorkloadsResponse) -> environments.ListWorkloadsResponse: + """Post-rpc interceptor for list_workloads + + DEPRECATED. Please use the `post_list_workloads_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_list_workloads` interceptor runs + before the `post_list_workloads_with_metadata` interceptor. + """ + return response + + def post_list_workloads_with_metadata(self, response: environments.ListWorkloadsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListWorkloadsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_workloads + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_list_workloads_with_metadata` + interceptor in new development instead of the `post_list_workloads` interceptor. + When both interceptors are used, this `post_list_workloads_with_metadata` interceptor runs after the + `post_list_workloads` interceptor. The (possibly modified) response returned by + `post_list_workloads` will be passed to + `post_list_workloads_with_metadata`. + """ + return response, metadata + + def pre_load_snapshot(self, request: environments.LoadSnapshotRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.LoadSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for load_snapshot + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_load_snapshot(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for load_snapshot + + DEPRECATED. Please use the `post_load_snapshot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_load_snapshot` interceptor runs + before the `post_load_snapshot_with_metadata` interceptor. + """ + return response + + def post_load_snapshot_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for load_snapshot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_load_snapshot_with_metadata` + interceptor in new development instead of the `post_load_snapshot` interceptor. + When both interceptors are used, this `post_load_snapshot_with_metadata` interceptor runs after the + `post_load_snapshot` interceptor. The (possibly modified) response returned by + `post_load_snapshot` will be passed to + `post_load_snapshot_with_metadata`. + """ + return response, metadata + + def pre_poll_airflow_command(self, request: environments.PollAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.PollAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for poll_airflow_command + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_poll_airflow_command(self, response: environments.PollAirflowCommandResponse) -> environments.PollAirflowCommandResponse: + """Post-rpc interceptor for poll_airflow_command + + DEPRECATED. Please use the `post_poll_airflow_command_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_poll_airflow_command` interceptor runs + before the `post_poll_airflow_command_with_metadata` interceptor. + """ + return response + + def post_poll_airflow_command_with_metadata(self, response: environments.PollAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.PollAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for poll_airflow_command + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_poll_airflow_command_with_metadata` + interceptor in new development instead of the `post_poll_airflow_command` interceptor. + When both interceptors are used, this `post_poll_airflow_command_with_metadata` interceptor runs after the + `post_poll_airflow_command` interceptor. The (possibly modified) response returned by + `post_poll_airflow_command` will be passed to + `post_poll_airflow_command_with_metadata`. + """ + return response, metadata + + def pre_save_snapshot(self, request: environments.SaveSnapshotRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.SaveSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for save_snapshot + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_save_snapshot(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for save_snapshot + + DEPRECATED. Please use the `post_save_snapshot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_save_snapshot` interceptor runs + before the `post_save_snapshot_with_metadata` interceptor. + """ + return response + + def post_save_snapshot_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for save_snapshot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_save_snapshot_with_metadata` + interceptor in new development instead of the `post_save_snapshot` interceptor. + When both interceptors are used, this `post_save_snapshot_with_metadata` interceptor runs after the + `post_save_snapshot` interceptor. The (possibly modified) response returned by + `post_save_snapshot` will be passed to + `post_save_snapshot_with_metadata`. + """ + return response, metadata + + def pre_stop_airflow_command(self, request: environments.StopAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.StopAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for stop_airflow_command + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_stop_airflow_command(self, response: environments.StopAirflowCommandResponse) -> environments.StopAirflowCommandResponse: + """Post-rpc interceptor for stop_airflow_command + + DEPRECATED. Please use the `post_stop_airflow_command_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_stop_airflow_command` interceptor runs + before the `post_stop_airflow_command_with_metadata` interceptor. + """ + return response + + def post_stop_airflow_command_with_metadata(self, response: environments.StopAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.StopAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for stop_airflow_command + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_stop_airflow_command_with_metadata` + interceptor in new development instead of the `post_stop_airflow_command` interceptor. + When both interceptors are used, this `post_stop_airflow_command_with_metadata` interceptor runs after the + `post_stop_airflow_command` interceptor. The (possibly modified) response returned by + `post_stop_airflow_command` will be passed to + `post_stop_airflow_command_with_metadata`. + """ + return response, metadata + + def pre_update_environment(self, request: environments.UpdateEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_environment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_update_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_environment + + DEPRECATED. Please use the `post_update_environment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_update_environment` interceptor runs + before the `post_update_environment_with_metadata` interceptor. + """ + return response + + def post_update_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_environment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_update_environment_with_metadata` + interceptor in new development instead of the `post_update_environment` interceptor. + When both interceptors are used, this `post_update_environment_with_metadata` interceptor runs after the + `post_update_environment` interceptor. The (possibly modified) response returned by + `post_update_environment` will be passed to + `post_update_environment_with_metadata`. + """ + return response, metadata + + def pre_update_user_workloads_config_map(self, request: environments.UpdateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_user_workloads_config_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_update_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: + """Post-rpc interceptor for update_user_workloads_config_map + + DEPRECATED. Please use the `post_update_user_workloads_config_map_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_update_user_workloads_config_map` interceptor runs + before the `post_update_user_workloads_config_map_with_metadata` interceptor. + """ + return response + + def post_update_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_user_workloads_config_map + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_update_user_workloads_config_map_with_metadata` + interceptor in new development instead of the `post_update_user_workloads_config_map` interceptor. + When both interceptors are used, this `post_update_user_workloads_config_map_with_metadata` interceptor runs after the + `post_update_user_workloads_config_map` interceptor. The (possibly modified) response returned by + `post_update_user_workloads_config_map` will be passed to + `post_update_user_workloads_config_map_with_metadata`. + """ + return response, metadata + + def pre_update_user_workloads_secret(self, request: environments.UpdateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_user_workloads_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_update_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: + """Post-rpc interceptor for update_user_workloads_secret + + DEPRECATED. Please use the `post_update_user_workloads_secret_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_update_user_workloads_secret` interceptor runs + before the `post_update_user_workloads_secret_with_metadata` interceptor. + """ + return response + + def post_update_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_user_workloads_secret + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_update_user_workloads_secret_with_metadata` + interceptor in new development instead of the `post_update_user_workloads_secret` interceptor. + When both interceptors are used, this `post_update_user_workloads_secret_with_metadata` interceptor runs after the + `post_update_user_workloads_secret` interceptor. The (possibly modified) response returned by + `post_update_user_workloads_secret` will be passed to + `post_update_user_workloads_secret_with_metadata`. + """ + return response, metadata + + 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 Environments 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 Environments 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 Environments 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 Environments 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 Environments 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 Environments server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EnvironmentsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EnvironmentsRestInterceptor + + +class EnvironmentsRestTransport(_BaseEnvironmentsRestTransport): + """REST backend synchronous transport for Environments. + + Managed Apache Airflow Environments. + + 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 = 'composer.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[EnvironmentsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'composer.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 EnvironmentsRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/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 _CheckUpgrade(_BaseEnvironmentsRestTransport._BaseCheckUpgrade, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.CheckUpgrade") + + @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: environments.CheckUpgradeRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the check upgrade method over HTTP. + + Args: + request (~.environments.CheckUpgradeRequest): + The request object. Request to check whether image + upgrade will succeed. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_http_options() + + request, metadata = self._interceptor.pre_check_upgrade(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._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.orchestration.airflow.service_v1.EnvironmentsClient.CheckUpgrade", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "CheckUpgrade", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._CheckUpgrade._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_check_upgrade(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_check_upgrade_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1.EnvironmentsClient.check_upgrade", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "CheckUpgrade", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateEnvironment(_BaseEnvironmentsRestTransport._BaseCreateEnvironment, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.CreateEnvironment") + + @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: environments.CreateEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create environment method over HTTP. + + Args: + request (~.environments.CreateEnvironmentRequest): + The request object. Create a new environment. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_http_options() + + request, metadata = self._interceptor.pre_create_environment(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._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.orchestration.airflow.service_v1.EnvironmentsClient.CreateEnvironment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "CreateEnvironment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._CreateEnvironment._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_environment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_environment_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1.EnvironmentsClient.create_environment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "CreateEnvironment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.CreateUserWorkloadsConfigMap") + + @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: environments.CreateUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsConfigMap: + r"""Call the create user workloads + config map method over HTTP. + + Args: + request (~.environments.CreateUserWorkloadsConfigMapRequest): + The request object. Create user workloads ConfigMap + request. + retry (google.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: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_http_options() + + request, metadata = self._interceptor.pre_create_user_workloads_config_map(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._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.orchestration.airflow.service_v1.EnvironmentsClient.CreateUserWorkloadsConfigMap", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "CreateUserWorkloadsConfigMap", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._CreateUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() + pb_resp = environments.UserWorkloadsConfigMap.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_user_workloads_config_map(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_user_workloads_config_map_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1.EnvironmentsClient.create_user_workloads_config_map", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "CreateUserWorkloadsConfigMap", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.CreateUserWorkloadsSecret") + + @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: environments.CreateUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsSecret: + r"""Call the create user workloads + secret method over HTTP. + + Args: + request (~.environments.CreateUserWorkloadsSecretRequest): + The request object. Create user workloads Secret request. + retry (google.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: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_http_options() + + request, metadata = self._interceptor.pre_create_user_workloads_secret(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._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.orchestration.airflow.service_v1.EnvironmentsClient.CreateUserWorkloadsSecret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "CreateUserWorkloadsSecret", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._CreateUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() + pb_resp = environments.UserWorkloadsSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_user_workloads_secret(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_user_workloads_secret_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1.EnvironmentsClient.create_user_workloads_secret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "CreateUserWorkloadsSecret", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DatabaseFailover(_BaseEnvironmentsRestTransport._BaseDatabaseFailover, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.DatabaseFailover") + + @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: environments.DatabaseFailoverRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the database failover method over HTTP. + + Args: + request (~.environments.DatabaseFailoverRequest): + The request object. Request to trigger database failover + (only for highly resilient + environments). + retry (google.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 = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_http_options() + + request, metadata = self._interceptor.pre_database_failover(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._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.orchestration.airflow.service_v1.EnvironmentsClient.DatabaseFailover", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "DatabaseFailover", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._DatabaseFailover._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_database_failover(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_database_failover_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1.EnvironmentsClient.database_failover", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "DatabaseFailover", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteEnvironment(_BaseEnvironmentsRestTransport._BaseDeleteEnvironment, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.DeleteEnvironment") + + @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: environments.DeleteEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete environment method over HTTP. + + Args: + request (~.environments.DeleteEnvironmentRequest): + The request object. Delete an environment. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_http_options() + + request, metadata = self._interceptor.pre_delete_environment(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._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.orchestration.airflow.service_v1.EnvironmentsClient.DeleteEnvironment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "DeleteEnvironment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._DeleteEnvironment._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_environment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_environment_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1.EnvironmentsClient.delete_environment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "DeleteEnvironment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.DeleteUserWorkloadsConfigMap") + + @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: environments.DeleteUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete user workloads + config map method over HTTP. + + Args: + request (~.environments.DeleteUserWorkloadsConfigMapRequest): + The request object. Delete user workloads ConfigMap + request. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_http_options() + + request, metadata = self._interceptor.pre_delete_user_workloads_config_map(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._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.orchestration.airflow.service_v1.EnvironmentsClient.DeleteUserWorkloadsConfigMap", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "DeleteUserWorkloadsConfigMap", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._DeleteUserWorkloadsConfigMap._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) + + class _DeleteUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.DeleteUserWorkloadsSecret") + + @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: environments.DeleteUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete user workloads + secret method over HTTP. + + Args: + request (~.environments.DeleteUserWorkloadsSecretRequest): + The request object. Delete user workloads Secret request. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_http_options() + + request, metadata = self._interceptor.pre_delete_user_workloads_secret(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._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.orchestration.airflow.service_v1.EnvironmentsClient.DeleteUserWorkloadsSecret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "DeleteUserWorkloadsSecret", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._DeleteUserWorkloadsSecret._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) + + class _ExecuteAirflowCommand(_BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.ExecuteAirflowCommand") + + @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: environments.ExecuteAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.ExecuteAirflowCommandResponse: + r"""Call the execute airflow command method over HTTP. + + Args: + request (~.environments.ExecuteAirflowCommandRequest): + The request object. Execute Airflow Command request. + retry (google.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: + ~.environments.ExecuteAirflowCommandResponse: + Response to + ExecuteAirflowCommandRequest. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_http_options() + + request, metadata = self._interceptor.pre_execute_airflow_command(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._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.orchestration.airflow.service_v1.EnvironmentsClient.ExecuteAirflowCommand", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ExecuteAirflowCommand", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._ExecuteAirflowCommand._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 = environments.ExecuteAirflowCommandResponse() + pb_resp = environments.ExecuteAirflowCommandResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_execute_airflow_command(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_execute_airflow_command_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.ExecuteAirflowCommandResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.execute_airflow_command", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ExecuteAirflowCommand", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchDatabaseProperties(_BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.FetchDatabaseProperties") + + @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: environments.FetchDatabasePropertiesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.FetchDatabasePropertiesResponse: + r"""Call the fetch database properties method over HTTP. + + Args: + request (~.environments.FetchDatabasePropertiesRequest): + The request object. Request to fetch properties of + environment's database. + retry (google.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: + ~.environments.FetchDatabasePropertiesResponse: + Response for + FetchDatabasePropertiesRequest. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_http_options() + + request, metadata = self._interceptor.pre_fetch_database_properties(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._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.orchestration.airflow.service_v1.EnvironmentsClient.FetchDatabaseProperties", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "FetchDatabaseProperties", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._FetchDatabaseProperties._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 = environments.FetchDatabasePropertiesResponse() + pb_resp = environments.FetchDatabasePropertiesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_database_properties(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_fetch_database_properties_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.FetchDatabasePropertiesResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.fetch_database_properties", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "FetchDatabaseProperties", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetEnvironment(_BaseEnvironmentsRestTransport._BaseGetEnvironment, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.GetEnvironment") + + @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: environments.GetEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.Environment: + r"""Call the get environment method over HTTP. + + Args: + request (~.environments.GetEnvironmentRequest): + The request object. Get an environment. + retry (google.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: + ~.environments.Environment: + An environment for running + orchestration tasks. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_http_options() + + request, metadata = self._interceptor.pre_get_environment(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseGetEnvironment._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.orchestration.airflow.service_v1.EnvironmentsClient.GetEnvironment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "GetEnvironment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._GetEnvironment._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 = environments.Environment() + pb_resp = environments.Environment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_environment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_environment_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.Environment.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.orchestration.airflow.service_v1.EnvironmentsClient.get_environment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "GetEnvironment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.GetUserWorkloadsConfigMap") + + @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: environments.GetUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsConfigMap: + r"""Call the get user workloads config + map method over HTTP. + + Args: + request (~.environments.GetUserWorkloadsConfigMapRequest): + The request object. Get user workloads ConfigMap request. + retry (google.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: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_http_options() + + request, metadata = self._interceptor.pre_get_user_workloads_config_map(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._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.orchestration.airflow.service_v1.EnvironmentsClient.GetUserWorkloadsConfigMap", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "GetUserWorkloadsConfigMap", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._GetUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() + pb_resp = environments.UserWorkloadsConfigMap.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_user_workloads_config_map(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_user_workloads_config_map_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1.EnvironmentsClient.get_user_workloads_config_map", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "GetUserWorkloadsConfigMap", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.GetUserWorkloadsSecret") + + @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: environments.GetUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsSecret: + r"""Call the get user workloads secret method over HTTP. + + Args: + request (~.environments.GetUserWorkloadsSecretRequest): + The request object. Get user workloads Secret request. + retry (google.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: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_http_options() + + request, metadata = self._interceptor.pre_get_user_workloads_secret(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._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.orchestration.airflow.service_v1.EnvironmentsClient.GetUserWorkloadsSecret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "GetUserWorkloadsSecret", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._GetUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() + pb_resp = environments.UserWorkloadsSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_user_workloads_secret(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_user_workloads_secret_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1.EnvironmentsClient.get_user_workloads_secret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "GetUserWorkloadsSecret", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListEnvironments(_BaseEnvironmentsRestTransport._BaseListEnvironments, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.ListEnvironments") + + @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: environments.ListEnvironmentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.ListEnvironmentsResponse: + r"""Call the list environments method over HTTP. + + Args: + request (~.environments.ListEnvironmentsRequest): + The request object. List environments in a project and + location. + retry (google.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: + ~.environments.ListEnvironmentsResponse: + The environments in a project and + location. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseListEnvironments._get_http_options() + + request, metadata = self._interceptor.pre_list_environments(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseListEnvironments._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseListEnvironments._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.orchestration.airflow.service_v1.EnvironmentsClient.ListEnvironments", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ListEnvironments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._ListEnvironments._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 = environments.ListEnvironmentsResponse() + pb_resp = environments.ListEnvironmentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_environments(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_environments_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.ListEnvironmentsResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.list_environments", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ListEnvironments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListUserWorkloadsConfigMaps(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.ListUserWorkloadsConfigMaps") + + @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: environments.ListUserWorkloadsConfigMapsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.ListUserWorkloadsConfigMapsResponse: + r"""Call the list user workloads + config maps method over HTTP. + + Args: + request (~.environments.ListUserWorkloadsConfigMapsRequest): + The request object. List user workloads ConfigMaps + request. + retry (google.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: + ~.environments.ListUserWorkloadsConfigMapsResponse: + The user workloads ConfigMaps for a + given environment. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_http_options() + + request, metadata = self._interceptor.pre_list_user_workloads_config_maps(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._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.orchestration.airflow.service_v1.EnvironmentsClient.ListUserWorkloadsConfigMaps", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ListUserWorkloadsConfigMaps", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._ListUserWorkloadsConfigMaps._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 = environments.ListUserWorkloadsConfigMapsResponse() + pb_resp = environments.ListUserWorkloadsConfigMapsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_user_workloads_config_maps(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_user_workloads_config_maps_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.ListUserWorkloadsConfigMapsResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.list_user_workloads_config_maps", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ListUserWorkloadsConfigMaps", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListUserWorkloadsSecrets(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.ListUserWorkloadsSecrets") + + @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: environments.ListUserWorkloadsSecretsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.ListUserWorkloadsSecretsResponse: + r"""Call the list user workloads + secrets method over HTTP. + + Args: + request (~.environments.ListUserWorkloadsSecretsRequest): + The request object. List user workloads Secrets request. + retry (google.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: + ~.environments.ListUserWorkloadsSecretsResponse: + The user workloads Secrets for a + given environment. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_http_options() + + request, metadata = self._interceptor.pre_list_user_workloads_secrets(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._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.orchestration.airflow.service_v1.EnvironmentsClient.ListUserWorkloadsSecrets", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ListUserWorkloadsSecrets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._ListUserWorkloadsSecrets._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 = environments.ListUserWorkloadsSecretsResponse() + pb_resp = environments.ListUserWorkloadsSecretsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_user_workloads_secrets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_user_workloads_secrets_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.ListUserWorkloadsSecretsResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.list_user_workloads_secrets", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ListUserWorkloadsSecrets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListWorkloads(_BaseEnvironmentsRestTransport._BaseListWorkloads, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.ListWorkloads") + + @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: environments.ListWorkloadsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.ListWorkloadsResponse: + r"""Call the list workloads method over HTTP. + + Args: + request (~.environments.ListWorkloadsRequest): + The request object. Request for listing workloads in a + Cloud Composer environment. + retry (google.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: + ~.environments.ListWorkloadsResponse: + Response to ListWorkloadsRequest. + """ + + http_options = _BaseEnvironmentsRestTransport._BaseListWorkloads._get_http_options() + + request, metadata = self._interceptor.pre_list_workloads(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseListWorkloads._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseListWorkloads._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.orchestration.airflow.service_v1.EnvironmentsClient.ListWorkloads", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ListWorkloads", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._ListWorkloads._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 = environments.ListWorkloadsResponse() + pb_resp = environments.ListWorkloadsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_workloads(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_workloads_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.ListWorkloadsResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.list_workloads", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ListWorkloads", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _LoadSnapshot(_BaseEnvironmentsRestTransport._BaseLoadSnapshot, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.LoadSnapshot") + + @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: environments.LoadSnapshotRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the load snapshot method over HTTP. + + Args: + request (~.environments.LoadSnapshotRequest): + The request object. Request to load a snapshot into a + Cloud Composer environment. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_http_options() + + request, metadata = self._interceptor.pre_load_snapshot(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._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.orchestration.airflow.service_v1.EnvironmentsClient.LoadSnapshot", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "LoadSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._LoadSnapshot._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_load_snapshot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_load_snapshot_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1.EnvironmentsClient.load_snapshot", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "LoadSnapshot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PollAirflowCommand(_BaseEnvironmentsRestTransport._BasePollAirflowCommand, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.PollAirflowCommand") + + @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: environments.PollAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.PollAirflowCommandResponse: + r"""Call the poll airflow command method over HTTP. + + Args: + request (~.environments.PollAirflowCommandRequest): + The request object. Poll Airflow Command request. + retry (google.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: + ~.environments.PollAirflowCommandResponse: + Response to + PollAirflowCommandRequest. + + """ + + http_options = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_http_options() + + request, metadata = self._interceptor.pre_poll_airflow_command(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._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.orchestration.airflow.service_v1.EnvironmentsClient.PollAirflowCommand", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "PollAirflowCommand", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._PollAirflowCommand._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 = environments.PollAirflowCommandResponse() + pb_resp = environments.PollAirflowCommandResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_poll_airflow_command(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_poll_airflow_command_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.PollAirflowCommandResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.poll_airflow_command", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "PollAirflowCommand", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SaveSnapshot(_BaseEnvironmentsRestTransport._BaseSaveSnapshot, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.SaveSnapshot") + + @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: environments.SaveSnapshotRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the save snapshot method over HTTP. + + Args: + request (~.environments.SaveSnapshotRequest): + The request object. Request to create a snapshot of a + Cloud Composer environment. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_http_options() + + request, metadata = self._interceptor.pre_save_snapshot(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._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.orchestration.airflow.service_v1.EnvironmentsClient.SaveSnapshot", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "SaveSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._SaveSnapshot._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_save_snapshot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_save_snapshot_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1.EnvironmentsClient.save_snapshot", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "SaveSnapshot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _StopAirflowCommand(_BaseEnvironmentsRestTransport._BaseStopAirflowCommand, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.StopAirflowCommand") + + @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: environments.StopAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.StopAirflowCommandResponse: + r"""Call the stop airflow command method over HTTP. + + Args: + request (~.environments.StopAirflowCommandRequest): + The request object. Stop Airflow Command request. + retry (google.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: + ~.environments.StopAirflowCommandResponse: + Response to + StopAirflowCommandRequest. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_http_options() + + request, metadata = self._interceptor.pre_stop_airflow_command(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._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.orchestration.airflow.service_v1.EnvironmentsClient.StopAirflowCommand", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "StopAirflowCommand", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._StopAirflowCommand._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 = environments.StopAirflowCommandResponse() + pb_resp = environments.StopAirflowCommandResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_stop_airflow_command(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_stop_airflow_command_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.StopAirflowCommandResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.stop_airflow_command", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "StopAirflowCommand", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateEnvironment(_BaseEnvironmentsRestTransport._BaseUpdateEnvironment, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.UpdateEnvironment") + + @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: environments.UpdateEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update environment method over HTTP. + + Args: + request (~.environments.UpdateEnvironmentRequest): + The request object. Update an environment. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_http_options() + + request, metadata = self._interceptor.pre_update_environment(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._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.orchestration.airflow.service_v1.EnvironmentsClient.UpdateEnvironment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "UpdateEnvironment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._UpdateEnvironment._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_environment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_environment_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1.EnvironmentsClient.update_environment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "UpdateEnvironment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.UpdateUserWorkloadsConfigMap") + + @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: environments.UpdateUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsConfigMap: + r"""Call the update user workloads + config map method over HTTP. + + Args: + request (~.environments.UpdateUserWorkloadsConfigMapRequest): + The request object. Update user workloads ConfigMap + request. + retry (google.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: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_http_options() + + request, metadata = self._interceptor.pre_update_user_workloads_config_map(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._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.orchestration.airflow.service_v1.EnvironmentsClient.UpdateUserWorkloadsConfigMap", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "UpdateUserWorkloadsConfigMap", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._UpdateUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() + pb_resp = environments.UserWorkloadsConfigMap.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_user_workloads_config_map(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_user_workloads_config_map_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1.EnvironmentsClient.update_user_workloads_config_map", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "UpdateUserWorkloadsConfigMap", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.UpdateUserWorkloadsSecret") + + @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: environments.UpdateUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsSecret: + r"""Call the update user workloads + secret method over HTTP. + + Args: + request (~.environments.UpdateUserWorkloadsSecretRequest): + The request object. Update user workloads Secret request. + retry (google.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: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_http_options() + + request, metadata = self._interceptor.pre_update_user_workloads_secret(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._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.orchestration.airflow.service_v1.EnvironmentsClient.UpdateUserWorkloadsSecret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "UpdateUserWorkloadsSecret", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._UpdateUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() + pb_resp = environments.UserWorkloadsSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_user_workloads_secret(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_user_workloads_secret_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1.EnvironmentsClient.update_user_workloads_secret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "UpdateUserWorkloadsSecret", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def check_upgrade(self) -> Callable[ + [environments.CheckUpgradeRequest], + 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._CheckUpgrade(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_environment(self) -> Callable[ + [environments.CreateEnvironmentRequest], + 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._CreateEnvironment(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_user_workloads_config_map(self) -> Callable[ + [environments.CreateUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + # 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._CreateUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_user_workloads_secret(self) -> Callable[ + [environments.CreateUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + # 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._CreateUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def database_failover(self) -> Callable[ + [environments.DatabaseFailoverRequest], + 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._DatabaseFailover(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_environment(self) -> Callable[ + [environments.DeleteEnvironmentRequest], + 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._DeleteEnvironment(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user_workloads_config_map(self) -> Callable[ + [environments.DeleteUserWorkloadsConfigMapRequest], + empty_pb2.Empty]: + # 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._DeleteUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user_workloads_secret(self) -> Callable[ + [environments.DeleteUserWorkloadsSecretRequest], + empty_pb2.Empty]: + # 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._DeleteUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def execute_airflow_command(self) -> Callable[ + [environments.ExecuteAirflowCommandRequest], + environments.ExecuteAirflowCommandResponse]: + # 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._ExecuteAirflowCommand(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_database_properties(self) -> Callable[ + [environments.FetchDatabasePropertiesRequest], + environments.FetchDatabasePropertiesResponse]: + # 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._FetchDatabaseProperties(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_environment(self) -> Callable[ + [environments.GetEnvironmentRequest], + environments.Environment]: + # 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._GetEnvironment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user_workloads_config_map(self) -> Callable[ + [environments.GetUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + # 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._GetUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user_workloads_secret(self) -> Callable[ + [environments.GetUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + # 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._GetUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_environments(self) -> Callable[ + [environments.ListEnvironmentsRequest], + environments.ListEnvironmentsResponse]: + # 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._ListEnvironments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_user_workloads_config_maps(self) -> Callable[ + [environments.ListUserWorkloadsConfigMapsRequest], + environments.ListUserWorkloadsConfigMapsResponse]: + # 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._ListUserWorkloadsConfigMaps(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_user_workloads_secrets(self) -> Callable[ + [environments.ListUserWorkloadsSecretsRequest], + environments.ListUserWorkloadsSecretsResponse]: + # 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._ListUserWorkloadsSecrets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workloads(self) -> Callable[ + [environments.ListWorkloadsRequest], + environments.ListWorkloadsResponse]: + # 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._ListWorkloads(self._session, self._host, self._interceptor) # type: ignore + + @property + def load_snapshot(self) -> Callable[ + [environments.LoadSnapshotRequest], + 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._LoadSnapshot(self._session, self._host, self._interceptor) # type: ignore + + @property + def poll_airflow_command(self) -> Callable[ + [environments.PollAirflowCommandRequest], + environments.PollAirflowCommandResponse]: + # 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._PollAirflowCommand(self._session, self._host, self._interceptor) # type: ignore + + @property + def save_snapshot(self) -> Callable[ + [environments.SaveSnapshotRequest], + 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._SaveSnapshot(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_airflow_command(self) -> Callable[ + [environments.StopAirflowCommandRequest], + environments.StopAirflowCommandResponse]: + # 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._StopAirflowCommand(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_environment(self) -> Callable[ + [environments.UpdateEnvironmentRequest], + 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._UpdateEnvironment(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user_workloads_config_map(self) -> Callable[ + [environments.UpdateUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + # 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._UpdateUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user_workloads_secret(self) -> Callable[ + [environments.UpdateUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + # 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._UpdateUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseEnvironmentsRestTransport._BaseDeleteOperation, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1.EnvironmentsClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._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(_BaseEnvironmentsRestTransport._BaseGetOperation, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1.EnvironmentsClient.GetOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._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.orchestration.airflow.service_v1.EnvironmentsAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "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(_BaseEnvironmentsRestTransport._BaseListOperations, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1.EnvironmentsClient.ListOperations", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._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.orchestration.airflow.service_v1.EnvironmentsAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", + "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__=( + 'EnvironmentsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest_base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest_base.py new file mode 100644 index 000000000000..288d7319af97 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest_base.py @@ -0,0 +1,1082 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 EnvironmentsTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.orchestration.airflow.service_v1.types import environments +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseEnvironmentsRestTransport(EnvironmentsTransport): + """Base REST backend transport for Environments. + + 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 = 'composer.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: 'composer.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 _BaseCheckUpgrade: + 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/{environment=projects/*/locations/*/environments/*}:checkUpgrade', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.CheckUpgradeRequest.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=True + ) + 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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateEnvironment: + 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/{parent=projects/*/locations/*}/environments', + 'body': 'environment', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.CreateEnvironmentRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateUserWorkloadsConfigMap: + 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/*/environments/*}/userWorkloadsConfigMaps', + 'body': 'user_workloads_config_map', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.CreateUserWorkloadsConfigMapRequest.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=True + ) + 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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateUserWorkloadsSecret: + 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/*/environments/*}/userWorkloadsSecrets', + 'body': 'user_workloads_secret', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.CreateUserWorkloadsSecretRequest.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=True + ) + 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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDatabaseFailover: + 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/{environment=projects/*/locations/*/environments/*}:databaseFailover', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.DatabaseFailoverRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteEnvironment: + 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/*/environments/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.DeleteEnvironmentRequest.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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteUserWorkloadsConfigMap: + 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/*/environments/*/userWorkloadsConfigMaps/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.DeleteUserWorkloadsConfigMapRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteUserWorkloadsSecret: + 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/*/environments/*/userWorkloadsSecrets/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.DeleteUserWorkloadsSecretRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExecuteAirflowCommand: + 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/{environment=projects/*/locations/*/environments/*}:executeAirflowCommand', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.ExecuteAirflowCommandRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFetchDatabaseProperties: + 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/{environment=projects/*/locations/*/environments/*}:fetchDatabaseProperties', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.FetchDatabasePropertiesRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEnvironment: + 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/*/environments/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.GetEnvironmentRequest.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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetUserWorkloadsConfigMap: + 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/*/environments/*/userWorkloadsConfigMaps/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.GetUserWorkloadsConfigMapRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetUserWorkloadsSecret: + 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/*/environments/*/userWorkloadsSecrets/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.GetUserWorkloadsSecretRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEnvironments: + 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/{parent=projects/*/locations/*}/environments', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.ListEnvironmentsRequest.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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUserWorkloadsConfigMaps: + 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/*/environments/*}/userWorkloadsConfigMaps', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.ListUserWorkloadsConfigMapsRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUserWorkloadsSecrets: + 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/*/environments/*}/userWorkloadsSecrets', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.ListUserWorkloadsSecretsRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListWorkloads: + 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/*/environments/*}/workloads', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.ListWorkloadsRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseListWorkloads._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseLoadSnapshot: + 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/{environment=projects/*/locations/*/environments/*}:loadSnapshot', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.LoadSnapshotRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePollAirflowCommand: + 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/{environment=projects/*/locations/*/environments/*}:pollAirflowCommand', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.PollAirflowCommandRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSaveSnapshot: + 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/{environment=projects/*/locations/*/environments/*}:saveSnapshot', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.SaveSnapshotRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStopAirflowCommand: + 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/{environment=projects/*/locations/*/environments/*}:stopAirflowCommand', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.StopAirflowCommandRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEnvironment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{name=projects/*/locations/*/environments/*}', + 'body': 'environment', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.UpdateEnvironmentRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateUserWorkloadsConfigMap: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'put', + 'uri': '/v1/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', + 'body': 'user_workloads_config_map', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.UpdateUserWorkloadsConfigMapRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateUserWorkloadsSecret: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'put', + 'uri': '/v1/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', + 'body': 'user_workloads_secret', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.UpdateUserWorkloadsSecretRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + 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__=( + '_BaseEnvironmentsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/__init__.py new file mode 100644 index 000000000000..cf004e25ae3f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/__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 ImageVersionsClient +from .async_client import ImageVersionsAsyncClient + +__all__ = ( + 'ImageVersionsClient', + 'ImageVersionsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/async_client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/async_client.py new file mode 100644 index 000000000000..91ef6c10b56f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/async_client.py @@ -0,0 +1,536 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_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.cloud.orchestration.airflow.service_v1.services.image_versions import pagers +from google.cloud.orchestration.airflow.service_v1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import ImageVersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ImageVersionsGrpcAsyncIOTransport +from .client import ImageVersionsClient + +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 ImageVersionsAsyncClient: + """Readonly service to query available ImageVersions.""" + + _client: ImageVersionsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ImageVersionsClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod(ImageVersionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ImageVersionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ImageVersionsClient.common_folder_path) + parse_common_folder_path = staticmethod(ImageVersionsClient.parse_common_folder_path) + common_organization_path = staticmethod(ImageVersionsClient.common_organization_path) + parse_common_organization_path = staticmethod(ImageVersionsClient.parse_common_organization_path) + common_project_path = staticmethod(ImageVersionsClient.common_project_path) + parse_common_project_path = staticmethod(ImageVersionsClient.parse_common_project_path) + common_location_path = staticmethod(ImageVersionsClient.common_location_path) + parse_common_location_path = staticmethod(ImageVersionsClient.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: + ImageVersionsAsyncClient: The constructed client. + """ + return ImageVersionsClient.from_service_account_info.__func__(ImageVersionsAsyncClient, 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: + ImageVersionsAsyncClient: The constructed client. + """ + return ImageVersionsClient.from_service_account_file.__func__(ImageVersionsAsyncClient, 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 ImageVersionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ImageVersionsTransport: + """Returns the transport used by the client instance. + + Returns: + ImageVersionsTransport: 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 = ImageVersionsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageVersionsTransport, Callable[..., ImageVersionsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the image versions 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,ImageVersionsTransport,Callable[..., ImageVersionsTransport]]]): + 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 ImageVersionsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ImageVersionsClient( + 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.orchestration.airflow.service_v1.ImageVersionsAsyncClient`.", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "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.orchestration.airflow.service.v1.ImageVersions", + "credentialsType": None, + } + ) + + async def list_image_versions(self, + request: Optional[Union[image_versions.ListImageVersionsRequest, 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.ListImageVersionsAsyncPager: + r"""List ImageVersions for provided 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.orchestration.airflow import service_v1 + + async def sample_list_image_versions(): + # Create a client + client = service_v1.ImageVersionsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ListImageVersionsRequest( + ) + + # Make the request + page_result = client.list_image_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest, dict]]): + The request object. List ImageVersions in a project and + location. + parent (:class:`str`): + List ImageVersions in the given + project and location, in the form: + "projects/{projectId}/locations/{locationId}" + + 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.orchestration.airflow.service_v1.services.image_versions.pagers.ListImageVersionsAsyncPager: + The ImageVersions in a project and + location. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, image_versions.ListImageVersionsRequest): + request = image_versions.ListImageVersionsRequest(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_image_versions] + + # 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.ListImageVersionsAsyncPager( + method=rpc, + request=request, + response=response, + 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 __aenter__(self) -> "ImageVersionsAsyncClient": + 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__ = ( + "ImageVersionsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py new file mode 100644 index 000000000000..38be91879394 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py @@ -0,0 +1,897 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +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.orchestration.airflow.service_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.cloud.orchestration.airflow.service_v1.services.image_versions import pagers +from google.cloud.orchestration.airflow.service_v1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import ImageVersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ImageVersionsGrpcTransport +from .transports.grpc_asyncio import ImageVersionsGrpcAsyncIOTransport +from .transports.rest import ImageVersionsRestTransport + + +class ImageVersionsClientMeta(type): + """Metaclass for the ImageVersions 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[ImageVersionsTransport]] + _transport_registry["grpc"] = ImageVersionsGrpcTransport + _transport_registry["grpc_asyncio"] = ImageVersionsGrpcAsyncIOTransport + _transport_registry["rest"] = ImageVersionsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ImageVersionsTransport]: + """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 ImageVersionsClient(metaclass=ImageVersionsClientMeta): + """Readonly service to query available ImageVersions.""" + + @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 = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "composer.{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: + ImageVersionsClient: 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: + ImageVersionsClient: 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) -> ImageVersionsTransport: + """Returns the transport used by the client instance. + + Returns: + ImageVersionsTransport: The transport used by the client + instance. + """ + return self._transport + + @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 = ImageVersionsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ImageVersionsClient._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 = ImageVersionsClient._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 + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @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, ImageVersionsTransport, Callable[..., ImageVersionsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the image versions 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,ImageVersionsTransport,Callable[..., ImageVersionsTransport]]]): + 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 ImageVersionsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ImageVersionsClient._read_environment_variables() + self._client_cert_source = ImageVersionsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ImageVersionsClient._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, ImageVersionsTransport) + if transport_provided: + # transport is a ImageVersionsTransport 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(ImageVersionsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ImageVersionsClient._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[ImageVersionsTransport], Callable[..., ImageVersionsTransport]] = ( + ImageVersionsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ImageVersionsTransport], 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.orchestration.airflow.service_v1.ImageVersionsClient`.", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "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.orchestration.airflow.service.v1.ImageVersions", + "credentialsType": None, + } + ) + + def list_image_versions(self, + request: Optional[Union[image_versions.ListImageVersionsRequest, 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.ListImageVersionsPager: + r"""List ImageVersions for provided 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.orchestration.airflow import service_v1 + + def sample_list_image_versions(): + # Create a client + client = service_v1.ImageVersionsClient() + + # Initialize request argument(s) + request = service_v1.ListImageVersionsRequest( + ) + + # Make the request + page_result = client.list_image_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest, dict]): + The request object. List ImageVersions in a project and + location. + parent (str): + List ImageVersions in the given + project and location, in the form: + "projects/{projectId}/locations/{locationId}" + + 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.orchestration.airflow.service_v1.services.image_versions.pagers.ListImageVersionsPager: + The ImageVersions in a project and + location. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, image_versions.ListImageVersionsRequest): + request = image_versions.ListImageVersionsRequest(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_image_versions] + + # 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.ListImageVersionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ImageVersionsClient": + 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() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + 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() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + 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,) + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ImageVersionsClient", +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/pagers.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/pagers.py new file mode 100644 index 000000000000..2dcaf6fac525 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1.types import image_versions + + +class ListImageVersionsPager: + """A pager for iterating through ``list_image_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``image_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListImageVersions`` requests and continue to iterate + through the ``image_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse` + 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[..., image_versions.ListImageVersionsResponse], + request: image_versions.ListImageVersionsRequest, + response: image_versions.ListImageVersionsResponse, + *, + 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.orchestration.airflow.service_v1.types.ListImageVersionsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse): + 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 = image_versions.ListImageVersionsRequest(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[image_versions.ListImageVersionsResponse]: + 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[image_versions.ImageVersion]: + for page in self.pages: + yield from page.image_versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListImageVersionsAsyncPager: + """A pager for iterating through ``list_image_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``image_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListImageVersions`` requests and continue to iterate + through the ``image_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse` + 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[image_versions.ListImageVersionsResponse]], + request: image_versions.ListImageVersionsRequest, + response: image_versions.ListImageVersionsResponse, + *, + 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.orchestration.airflow.service_v1.types.ListImageVersionsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse): + 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 = image_versions.ListImageVersionsRequest(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[image_versions.ListImageVersionsResponse]: + 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[image_versions.ImageVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.image_versions: + 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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/README.rst new file mode 100644 index 000000000000..8d4dc0e29401 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ImageVersionsTransport` is the ABC for all transports. +- public child `ImageVersionsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ImageVersionsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseImageVersionsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ImageVersionsRestTransport` 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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/__init__.py new file mode 100644 index 000000000000..5ab47c371986 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/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 ImageVersionsTransport +from .grpc import ImageVersionsGrpcTransport +from .grpc_asyncio import ImageVersionsGrpcAsyncIOTransport +from .rest import ImageVersionsRestTransport +from .rest import ImageVersionsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ImageVersionsTransport]] +_transport_registry['grpc'] = ImageVersionsGrpcTransport +_transport_registry['grpc_asyncio'] = ImageVersionsGrpcAsyncIOTransport +_transport_registry['rest'] = ImageVersionsRestTransport + +__all__ = ( + 'ImageVersionsTransport', + 'ImageVersionsGrpcTransport', + 'ImageVersionsGrpcAsyncIOTransport', + 'ImageVersionsRestTransport', + 'ImageVersionsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/base.py new file mode 100644 index 000000000000..09eff503a215 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/base.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_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.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.orchestration.airflow.service_v1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ImageVersionsTransport(abc.ABC): + """Abstract transport class for ImageVersions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'composer.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: 'composer.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_image_versions: gapic_v1.method.wrap_method( + self.list_image_versions, + 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 list_image_versions(self) -> Callable[ + [image_versions.ListImageVersionsRequest], + Union[ + image_versions.ListImageVersionsResponse, + Awaitable[image_versions.ListImageVersionsResponse] + ]]: + 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 delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ImageVersionsTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc.py new file mode 100644 index 000000000000..8c30881bbf8d --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc.py @@ -0,0 +1,402 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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.orchestration.airflow.service_v1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageVersionsTransport, 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.orchestration.airflow.service.v1.ImageVersions", + "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.orchestration.airflow.service.v1.ImageVersions", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ImageVersionsGrpcTransport(ImageVersionsTransport): + """gRPC backend transport for ImageVersions. + + Readonly service to query available ImageVersions. + + 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 = 'composer.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: 'composer.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] = {} + + 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 = 'composer.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 list_image_versions(self) -> Callable[ + [image_versions.ListImageVersionsRequest], + image_versions.ListImageVersionsResponse]: + r"""Return a callable for the list image versions method over gRPC. + + List ImageVersions for provided location. + + Returns: + Callable[[~.ListImageVersionsRequest], + ~.ListImageVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_image_versions' not in self._stubs: + self._stubs['list_image_versions'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.ImageVersions/ListImageVersions', + request_serializer=image_versions.ListImageVersionsRequest.serialize, + response_deserializer=image_versions.ListImageVersionsResponse.deserialize, + ) + return self._stubs['list_image_versions'] + + 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 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__ = ( + 'ImageVersionsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc_asyncio.py new file mode 100644 index 000000000000..d16d24e25d79 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc_asyncio.py @@ -0,0 +1,437 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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.orchestration.airflow.service_v1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import ImageVersionsGrpcTransport + +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.orchestration.airflow.service.v1.ImageVersions", + "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.orchestration.airflow.service.v1.ImageVersions", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ImageVersionsGrpcAsyncIOTransport(ImageVersionsTransport): + """gRPC AsyncIO backend transport for ImageVersions. + + Readonly service to query available ImageVersions. + + 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 = 'composer.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 = 'composer.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: 'composer.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] = {} + + 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 list_image_versions(self) -> Callable[ + [image_versions.ListImageVersionsRequest], + Awaitable[image_versions.ListImageVersionsResponse]]: + r"""Return a callable for the list image versions method over gRPC. + + List ImageVersions for provided location. + + Returns: + Callable[[~.ListImageVersionsRequest], + Awaitable[~.ListImageVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_image_versions' not in self._stubs: + self._stubs['list_image_versions'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1.ImageVersions/ListImageVersions', + request_serializer=image_versions.ListImageVersionsRequest.serialize, + response_deserializer=image_versions.ListImageVersionsResponse.deserialize, + ) + return self._stubs['list_image_versions'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_image_versions: self._wrap_method( + self.list_image_versions, + 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 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__ = ( + 'ImageVersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest.py new file mode 100644 index 000000000000..e33feadced89 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest.py @@ -0,0 +1,742 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.orchestration.airflow.service_v1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseImageVersionsRestTransport +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 ImageVersionsRestInterceptor: + """Interceptor for ImageVersions. + + 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 ImageVersionsRestTransport. + + .. code-block:: python + class MyCustomImageVersionsInterceptor(ImageVersionsRestInterceptor): + def pre_list_image_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_image_versions(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ImageVersionsRestTransport(interceptor=MyCustomImageVersionsInterceptor()) + client = ImageVersionsClient(transport=transport) + + + """ + def pre_list_image_versions(self, request: image_versions.ListImageVersionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_versions.ListImageVersionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_image_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the ImageVersions server. + """ + return request, metadata + + def post_list_image_versions(self, response: image_versions.ListImageVersionsResponse) -> image_versions.ListImageVersionsResponse: + """Post-rpc interceptor for list_image_versions + + DEPRECATED. Please use the `post_list_image_versions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ImageVersions server but before + it is returned to user code. This `post_list_image_versions` interceptor runs + before the `post_list_image_versions_with_metadata` interceptor. + """ + return response + + def post_list_image_versions_with_metadata(self, response: image_versions.ListImageVersionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_versions.ListImageVersionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_image_versions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ImageVersions server but before it is returned to user code. + + We recommend only using this `post_list_image_versions_with_metadata` + interceptor in new development instead of the `post_list_image_versions` interceptor. + When both interceptors are used, this `post_list_image_versions_with_metadata` interceptor runs after the + `post_list_image_versions` interceptor. The (possibly modified) response returned by + `post_list_image_versions` will be passed to + `post_list_image_versions_with_metadata`. + """ + return response, metadata + + 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ImageVersionsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ImageVersionsRestInterceptor + + +class ImageVersionsRestTransport(_BaseImageVersionsRestTransport): + """REST backend synchronous transport for ImageVersions. + + Readonly service to query available ImageVersions. + + 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 = 'composer.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[ImageVersionsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'composer.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) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ImageVersionsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ListImageVersions(_BaseImageVersionsRestTransport._BaseListImageVersions, ImageVersionsRestStub): + def __hash__(self): + return hash("ImageVersionsRestTransport.ListImageVersions") + + @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: image_versions.ListImageVersionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> image_versions.ListImageVersionsResponse: + r"""Call the list image versions method over HTTP. + + Args: + request (~.image_versions.ListImageVersionsRequest): + The request object. List ImageVersions in a project and + location. + retry (google.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: + ~.image_versions.ListImageVersionsResponse: + The ImageVersions in a project and + location. + + """ + + http_options = _BaseImageVersionsRestTransport._BaseListImageVersions._get_http_options() + + request, metadata = self._interceptor.pre_list_image_versions(request, metadata) + transcoded_request = _BaseImageVersionsRestTransport._BaseListImageVersions._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseImageVersionsRestTransport._BaseListImageVersions._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.orchestration.airflow.service_v1.ImageVersionsClient.ListImageVersions", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "rpcName": "ListImageVersions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ImageVersionsRestTransport._ListImageVersions._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 = image_versions.ListImageVersionsResponse() + pb_resp = image_versions.ListImageVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_image_versions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_image_versions_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = image_versions.ListImageVersionsResponse.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.orchestration.airflow.service_v1.ImageVersionsClient.list_image_versions", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "rpcName": "ListImageVersions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def list_image_versions(self) -> Callable[ + [image_versions.ListImageVersionsRequest], + image_versions.ListImageVersionsResponse]: + # 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._ListImageVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseImageVersionsRestTransport._BaseDeleteOperation, ImageVersionsRestStub): + def __hash__(self): + return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseImageVersionsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1.ImageVersionsClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ImageVersionsRestTransport._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(_BaseImageVersionsRestTransport._BaseGetOperation, ImageVersionsRestStub): + def __hash__(self): + return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseImageVersionsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1.ImageVersionsClient.GetOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ImageVersionsRestTransport._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.orchestration.airflow.service_v1.ImageVersionsAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "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(_BaseImageVersionsRestTransport._BaseListOperations, ImageVersionsRestStub): + def __hash__(self): + return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseImageVersionsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1.ImageVersionsClient.ListOperations", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ImageVersionsRestTransport._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.orchestration.airflow.service_v1.ImageVersionsAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "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__=( + 'ImageVersionsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest_base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest_base.py new file mode 100644 index 000000000000..4698fbffe626 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest_base.py @@ -0,0 +1,196 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ImageVersionsTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.orchestration.airflow.service_v1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseImageVersionsRestTransport(ImageVersionsTransport): + """Base REST backend transport for ImageVersions. + + 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 = 'composer.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: 'composer.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 _BaseListImageVersions: + 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/{parent=projects/*/locations/*}/imageVersions', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = image_versions.ListImageVersionsRequest.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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + 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__=( + '_BaseImageVersionsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py new file mode 100644 index 000000000000..3105fb19469d --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .environments import ( + AirflowMetadataRetentionPolicyConfig, + CheckUpgradeRequest, + CheckUpgradeResponse, + CloudDataLineageIntegration, + CreateEnvironmentRequest, + CreateUserWorkloadsConfigMapRequest, + CreateUserWorkloadsSecretRequest, + DatabaseConfig, + DatabaseFailoverRequest, + DatabaseFailoverResponse, + DataRetentionConfig, + DeleteEnvironmentRequest, + DeleteUserWorkloadsConfigMapRequest, + DeleteUserWorkloadsSecretRequest, + EncryptionConfig, + Environment, + EnvironmentConfig, + ExecuteAirflowCommandRequest, + ExecuteAirflowCommandResponse, + FetchDatabasePropertiesRequest, + FetchDatabasePropertiesResponse, + GetEnvironmentRequest, + GetUserWorkloadsConfigMapRequest, + GetUserWorkloadsSecretRequest, + IPAllocationPolicy, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + ListUserWorkloadsConfigMapsRequest, + ListUserWorkloadsConfigMapsResponse, + ListUserWorkloadsSecretsRequest, + ListUserWorkloadsSecretsResponse, + ListWorkloadsRequest, + ListWorkloadsResponse, + LoadSnapshotRequest, + LoadSnapshotResponse, + MaintenanceWindow, + MasterAuthorizedNetworksConfig, + NetworkingConfig, + NodeConfig, + PollAirflowCommandRequest, + PollAirflowCommandResponse, + PrivateClusterConfig, + PrivateEnvironmentConfig, + RecoveryConfig, + SaveSnapshotRequest, + SaveSnapshotResponse, + ScheduledSnapshotsConfig, + SoftwareConfig, + StopAirflowCommandRequest, + StopAirflowCommandResponse, + StorageConfig, + TaskLogsRetentionConfig, + UpdateEnvironmentRequest, + UpdateUserWorkloadsConfigMapRequest, + UpdateUserWorkloadsSecretRequest, + UserWorkloadsConfigMap, + UserWorkloadsSecret, + WebServerConfig, + WebServerNetworkAccessControl, + WorkloadsConfig, +) +from .image_versions import ( + ImageVersion, + ListImageVersionsRequest, + ListImageVersionsResponse, +) +from .operations import ( + OperationMetadata, +) + +__all__ = ( + 'AirflowMetadataRetentionPolicyConfig', + 'CheckUpgradeRequest', + 'CheckUpgradeResponse', + 'CloudDataLineageIntegration', + 'CreateEnvironmentRequest', + 'CreateUserWorkloadsConfigMapRequest', + 'CreateUserWorkloadsSecretRequest', + 'DatabaseConfig', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'DataRetentionConfig', + 'DeleteEnvironmentRequest', + 'DeleteUserWorkloadsConfigMapRequest', + 'DeleteUserWorkloadsSecretRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'GetEnvironmentRequest', + 'GetUserWorkloadsConfigMapRequest', + 'GetUserWorkloadsSecretRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'ListUserWorkloadsConfigMapsRequest', + 'ListUserWorkloadsConfigMapsResponse', + 'ListUserWorkloadsSecretsRequest', + 'ListUserWorkloadsSecretsResponse', + 'ListWorkloadsRequest', + 'ListWorkloadsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'StorageConfig', + 'TaskLogsRetentionConfig', + 'UpdateEnvironmentRequest', + 'UpdateUserWorkloadsConfigMapRequest', + 'UpdateUserWorkloadsSecretRequest', + 'UserWorkloadsConfigMap', + 'UserWorkloadsSecret', + 'WebServerConfig', + 'WebServerNetworkAccessControl', + 'WorkloadsConfig', + 'ImageVersion', + 'ListImageVersionsRequest', + 'ListImageVersionsResponse', + 'OperationMetadata', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py new file mode 100644 index 000000000000..10b50b735f1e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py @@ -0,0 +1,3089 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.orchestration.airflow.service.v1', + manifest={ + 'CreateEnvironmentRequest', + 'GetEnvironmentRequest', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'DeleteEnvironmentRequest', + 'UpdateEnvironmentRequest', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'CreateUserWorkloadsSecretRequest', + 'GetUserWorkloadsSecretRequest', + 'ListUserWorkloadsSecretsRequest', + 'UpdateUserWorkloadsSecretRequest', + 'DeleteUserWorkloadsSecretRequest', + 'CreateUserWorkloadsConfigMapRequest', + 'GetUserWorkloadsConfigMapRequest', + 'ListUserWorkloadsConfigMapsRequest', + 'UpdateUserWorkloadsConfigMapRequest', + 'DeleteUserWorkloadsConfigMapRequest', + 'UserWorkloadsSecret', + 'ListUserWorkloadsSecretsResponse', + 'UserWorkloadsConfigMap', + 'ListUserWorkloadsConfigMapsResponse', + 'ListWorkloadsRequest', + 'ListWorkloadsResponse', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'StorageConfig', + 'EnvironmentConfig', + 'WebServerNetworkAccessControl', + 'DatabaseConfig', + 'WebServerConfig', + 'EncryptionConfig', + 'MaintenanceWindow', + 'SoftwareConfig', + 'IPAllocationPolicy', + 'NodeConfig', + 'PrivateClusterConfig', + 'NetworkingConfig', + 'PrivateEnvironmentConfig', + 'WorkloadsConfig', + 'RecoveryConfig', + 'ScheduledSnapshotsConfig', + 'MasterAuthorizedNetworksConfig', + 'CloudDataLineageIntegration', + 'Environment', + 'CheckUpgradeRequest', + 'CheckUpgradeResponse', + 'DataRetentionConfig', + 'TaskLogsRetentionConfig', + 'AirflowMetadataRetentionPolicyConfig', + }, +) + + +class CreateEnvironmentRequest(proto.Message): + r"""Create a new environment. + + Attributes: + parent (str): + The parent must be of the form + "projects/{projectId}/locations/{locationId}". + environment (google.cloud.orchestration.airflow.service_v1.types.Environment): + The environment to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + environment: 'Environment' = proto.Field( + proto.MESSAGE, + number=2, + message='Environment', + ) + + +class GetEnvironmentRequest(proto.Message): + r"""Get an environment. + + Attributes: + name (str): + The resource name of the environment to get, + in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEnvironmentsRequest(proto.Message): + r"""List environments in a project and location. + + Attributes: + parent (str): + List environments in the given project and + location, in the form: + "projects/{projectId}/locations/{locationId}". + page_size (int): + The maximum number of environments to return. + page_token (str): + The next_page_token value returned from a previous List + 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 ListEnvironmentsResponse(proto.Message): + r"""The environments in a project and location. + + Attributes: + environments (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.Environment]): + The list of environments returned by a + ListEnvironmentsRequest. + next_page_token (str): + The page token used to query for the next + page if one exists. + """ + + @property + def raw_page(self): + return self + + environments: MutableSequence['Environment'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Environment', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteEnvironmentRequest(proto.Message): + r"""Delete an environment. + + Attributes: + name (str): + The environment to delete, in the form: + + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateEnvironmentRequest(proto.Message): + r"""Update an environment. + + Attributes: + name (str): + The relative resource name of the environment + to update, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + environment (google.cloud.orchestration.airflow.service_v1.types.Environment): + A patch environment. Fields specified by the ``updateMask`` + will be copied from the patch environment into the + environment under update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of paths, relative to + ``Environment``, of fields to update. For example, to set + the version of scikit-learn to install in the environment to + 0.19.0 and to remove an existing installation of numpy, the + ``updateMask`` parameter would include the following two + ``paths`` values: + "config.softwareConfig.pypiPackages.scikit-learn" and + "config.softwareConfig.pypiPackages.numpy". The included + patch environment would specify the scikit-learn version as + follows: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "scikit-learn":"==0.19.0" + } + } + } + } + + Note that in the above example, any existing PyPI packages + other than scikit-learn and numpy will be unaffected. + + Only one update type may be included in a single request's + ``updateMask``. For example, one cannot update both the PyPI + packages and labels in the same request. However, it is + possible to update multiple members of a map field + simultaneously in the same request. For example, to set the + labels "label1" and "label2" while clearing "label3" + (assuming it already exists), one can provide the paths + "labels.label1", "labels.label2", and "labels.label3" and + populate the patch environment as follows: + + :: + + { + "labels":{ + "label1":"new-label1-value" + "label2":"new-label2-value" + } + } + + Note that in the above example, any existing labels that are + not included in the ``updateMask`` will be unaffected. + + It is also possible to replace an entire map field by + providing the map field's path in the ``updateMask``. The + new value of the field will be that which is provided in the + patch environment. For example, to delete all pre-existing + user-specified PyPI packages and install botocore at version + 1.7.14, the ``updateMask`` would contain the path + "config.softwareConfig.pypiPackages", and the patch + environment would be the following: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "botocore":"==1.7.14" + } + } + } + } + + **Note:** Only the following fields can be updated: + + - ``config.softwareConfig.pypiPackages`` + + - Replace all custom custom PyPI packages. If a + replacement package map is not included in + ``environment``, all custom PyPI packages are cleared. + It is an error to provide both this mask and a mask + specifying an individual package. + + - ``config.softwareConfig.pypiPackages.``\ packagename + + - Update the custom PyPI package *packagename*, + preserving other packages. To delete the package, + include it in ``updateMask``, and omit the mapping for + it in + ``environment.config.softwareConfig.pypiPackages``. It + is an error to provide both a mask of this form and + the ``config.softwareConfig.pypiPackages`` mask. + + - ``labels`` + + - Replace all environment labels. If a replacement + labels map is not included in ``environment``, all + labels are cleared. It is an error to provide both + this mask and a mask specifying one or more individual + labels. + + - ``labels.``\ labelName + + - Set the label named *labelName*, while preserving + other labels. To delete the label, include it in + ``updateMask`` and omit its mapping in + ``environment.labels``. It is an error to provide both + a mask of this form and the ``labels`` mask. + + - ``config.nodeCount`` + + - Horizontally scale the number of nodes in the + environment. An integer greater than or equal to 3 + must be provided in the ``config.nodeCount`` field. + Supported for Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerNetworkAccessControl`` + + - Replace the environment's current + ``WebServerNetworkAccessControl``. + + - ``config.softwareConfig.airflowConfigOverrides`` + + - Replace all Apache Airflow config overrides. If a + replacement config overrides map is not included in + ``environment``, all config overrides are cleared. It + is an error to provide both this mask and a mask + specifying one or more individual config overrides. + + - ``config.softwareConfig.airflowConfigOverrides.``\ section-name + + - Override the Apache Airflow config property *name* in + the section named *section*, preserving other + properties. To delete the property override, include + it in ``updateMask`` and omit its mapping in + ``environment.config.softwareConfig.airflowConfigOverrides``. + It is an error to provide both a mask of this form and + the ``config.softwareConfig.airflowConfigOverrides`` + mask. + + - ``config.softwareConfig.envVariables`` + + - Replace all environment variables. If a replacement + environment variable map is not included in + ``environment``, all custom environment variables are + cleared. + + - ``config.softwareConfig.schedulerCount`` + + - Horizontally scale the number of schedulers in + Airflow. A positive integer not greater than the + number of nodes must be provided in the + ``config.softwareConfig.schedulerCount`` field. + Supported for Cloud Composer environments in versions + composer-1.\ *.*-airflow-2.*.*. + + - ``config.databaseConfig.machineType`` + + - Cloud SQL machine type used by Airflow database. It + has to be one of: db-n1-standard-2, db-n1-standard-4, + db-n1-standard-8 or db-n1-standard-16. Supported for + Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerConfig.machineType`` + + - Machine type on which Airflow web server is running. + It has to be one of: composer-n1-webserver-2, + composer-n1-webserver-4 or composer-n1-webserver-8. + Supported for Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + """ + + name: str = proto.Field( + proto.STRING, + number=2, + ) + environment: 'Environment' = proto.Field( + proto.MESSAGE, + number=1, + message='Environment', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class ExecuteAirflowCommandRequest(proto.Message): + r"""Execute Airflow Command request. + + Attributes: + environment (str): + The resource name of the environment in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + command (str): + Airflow command. + subcommand (str): + Airflow subcommand. + parameters (MutableSequence[str]): + Parameters for the Airflow command/subcommand as an array of + arguments. It may contain positional arguments like + ``["my-dag-id"]``, key-value parameters like + ``["--foo=bar"]`` or ``["--foo","bar"]``, or other flags + like ``["-f"]``. + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + command: str = proto.Field( + proto.STRING, + number=2, + ) + subcommand: str = proto.Field( + proto.STRING, + number=3, + ) + parameters: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class ExecuteAirflowCommandResponse(proto.Message): + r"""Response to ExecuteAirflowCommandRequest. + + Attributes: + execution_id (str): + The unique ID of the command execution for + polling. + pod (str): + The name of the pod where the command is + executed. + pod_namespace (str): + The namespace of the pod where the command is + executed. + error (str): + Error message. Empty if there was no error. + """ + + execution_id: str = proto.Field( + proto.STRING, + number=1, + ) + pod: str = proto.Field( + proto.STRING, + number=2, + ) + pod_namespace: str = proto.Field( + proto.STRING, + number=3, + ) + error: str = proto.Field( + proto.STRING, + number=4, + ) + + +class StopAirflowCommandRequest(proto.Message): + r"""Stop Airflow Command request. + + Attributes: + environment (str): + The resource name of the environment in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + execution_id (str): + The unique ID of the command execution. + pod (str): + The name of the pod where the command is + executed. + pod_namespace (str): + The namespace of the pod where the command is + executed. + force (bool): + If true, the execution is terminated + forcefully (SIGKILL). If false, the execution is + stopped gracefully, giving it time for cleanup. + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + execution_id: str = proto.Field( + proto.STRING, + number=2, + ) + pod: str = proto.Field( + proto.STRING, + number=3, + ) + pod_namespace: str = proto.Field( + proto.STRING, + number=4, + ) + force: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class StopAirflowCommandResponse(proto.Message): + r"""Response to StopAirflowCommandRequest. + + Attributes: + is_done (bool): + Whether the execution is still running. + output (MutableSequence[str]): + Output message from stopping execution + request. + """ + + is_done: bool = proto.Field( + proto.BOOL, + number=1, + ) + output: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class PollAirflowCommandRequest(proto.Message): + r"""Poll Airflow Command request. + + Attributes: + environment (str): + The resource name of the environment in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + execution_id (str): + The unique ID of the command execution. + pod (str): + The name of the pod where the command is + executed. + pod_namespace (str): + The namespace of the pod where the command is + executed. + next_line_number (int): + Line number from which new logs should be + fetched. + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + execution_id: str = proto.Field( + proto.STRING, + number=2, + ) + pod: str = proto.Field( + proto.STRING, + number=3, + ) + pod_namespace: str = proto.Field( + proto.STRING, + number=4, + ) + next_line_number: int = proto.Field( + proto.INT32, + number=5, + ) + + +class PollAirflowCommandResponse(proto.Message): + r"""Response to PollAirflowCommandRequest. + + Attributes: + output (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandResponse.Line]): + Output from the command execution. It may not + contain the full output and the caller may need + to poll for more lines. + output_end (bool): + Whether the command execution has finished + and there is no more output. + exit_info (google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandResponse.ExitInfo): + The result exit status of the command. + """ + + class Line(proto.Message): + r"""Contains information about a single line from logs. + + Attributes: + line_number (int): + Number of the line. + content (str): + Text content of the log line. + """ + + line_number: int = proto.Field( + proto.INT32, + number=1, + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + + class ExitInfo(proto.Message): + r"""Information about how a command ended. + + Attributes: + exit_code (int): + The exit code from the command execution. + error (str): + Error message. Empty if there was no error. + """ + + exit_code: int = proto.Field( + proto.INT32, + number=1, + ) + error: str = proto.Field( + proto.STRING, + number=2, + ) + + output: MutableSequence[Line] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Line, + ) + output_end: bool = proto.Field( + proto.BOOL, + number=2, + ) + exit_info: ExitInfo = proto.Field( + proto.MESSAGE, + number=3, + message=ExitInfo, + ) + + +class CreateUserWorkloadsSecretRequest(proto.Message): + r"""Create user workloads Secret request. + + Attributes: + parent (str): + Required. The environment name to create a + Secret for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + user_workloads_secret (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret): + Required. User workloads Secret to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_workloads_secret: 'UserWorkloadsSecret' = proto.Field( + proto.MESSAGE, + number=2, + message='UserWorkloadsSecret', + ) + + +class GetUserWorkloadsSecretRequest(proto.Message): + r"""Get user workloads Secret request. + + Attributes: + name (str): + Required. The resource name of the Secret to + get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListUserWorkloadsSecretsRequest(proto.Message): + r"""List user workloads Secrets request. + + Attributes: + parent (str): + Required. List Secrets in the given + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + page_size (int): + Optional. The maximum number of Secrets to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List 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 UpdateUserWorkloadsSecretRequest(proto.Message): + r"""Update user workloads Secret request. + + Attributes: + user_workloads_secret (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret): + Optional. User workloads Secret to override. + """ + + user_workloads_secret: 'UserWorkloadsSecret' = proto.Field( + proto.MESSAGE, + number=1, + message='UserWorkloadsSecret', + ) + + +class DeleteUserWorkloadsSecretRequest(proto.Message): + r"""Delete user workloads Secret request. + + Attributes: + name (str): + Required. The Secret to delete, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateUserWorkloadsConfigMapRequest(proto.Message): + r"""Create user workloads ConfigMap request. + + Attributes: + parent (str): + Required. The environment name to create a + ConfigMap for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + user_workloads_config_map (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap): + Required. User workloads ConfigMap to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_workloads_config_map: 'UserWorkloadsConfigMap' = proto.Field( + proto.MESSAGE, + number=2, + message='UserWorkloadsConfigMap', + ) + + +class GetUserWorkloadsConfigMapRequest(proto.Message): + r"""Get user workloads ConfigMap request. + + Attributes: + name (str): + Required. The resource name of the ConfigMap + to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListUserWorkloadsConfigMapsRequest(proto.Message): + r"""List user workloads ConfigMaps request. + + Attributes: + parent (str): + Required. List ConfigMaps in the given + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + page_size (int): + Optional. The maximum number of ConfigMaps to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List 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 UpdateUserWorkloadsConfigMapRequest(proto.Message): + r"""Update user workloads ConfigMap request. + + Attributes: + user_workloads_config_map (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap): + Optional. User workloads ConfigMap to + override. + """ + + user_workloads_config_map: 'UserWorkloadsConfigMap' = proto.Field( + proto.MESSAGE, + number=1, + message='UserWorkloadsConfigMap', + ) + + +class DeleteUserWorkloadsConfigMapRequest(proto.Message): + r"""Delete user workloads ConfigMap request. + + Attributes: + name (str): + Required. The ConfigMap to delete, in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UserWorkloadsSecret(proto.Message): + r"""User workloads Secret used by Airflow tasks that run with + Kubernetes executor or KubernetesPodOperator. + + Attributes: + name (str): + Identifier. The resource name of the Secret, + in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". + data (MutableMapping[str, str]): + Optional. The "data" field of Kubernetes + Secret, organized in key-value pairs, which can + contain sensitive values such as a password, a + token, or a key. The values for all keys have to + be base64-encoded strings. For details see: + https://kubernetes.io/docs/concepts/configuration/secret/ + + Example: + + { + "example": "ZXhhbXBsZV92YWx1ZQ==", + "another-example": + "YW5vdGhlcl9leGFtcGxlX3ZhbHVl" } + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +class ListUserWorkloadsSecretsResponse(proto.Message): + r"""The user workloads Secrets for a given environment. + + Attributes: + user_workloads_secrets (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret]): + The list of Secrets returned by a + ListUserWorkloadsSecretsRequest. + next_page_token (str): + The page token used to query for the next + page if one exists. + """ + + @property + def raw_page(self): + return self + + user_workloads_secrets: MutableSequence['UserWorkloadsSecret'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='UserWorkloadsSecret', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UserWorkloadsConfigMap(proto.Message): + r"""User workloads ConfigMap used by Airflow tasks that run with + Kubernetes executor or KubernetesPodOperator. + + Attributes: + name (str): + Identifier. The resource name of the + ConfigMap, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". + data (MutableMapping[str, str]): + Optional. The "data" field of Kubernetes ConfigMap, + organized in key-value pairs. For details see: + https://kubernetes.io/docs/concepts/configuration/configmap/ + + Example: + + { "example_key": "example_value", "another_key": + "another_value" } + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +class ListUserWorkloadsConfigMapsResponse(proto.Message): + r"""The user workloads ConfigMaps for a given environment. + + Attributes: + user_workloads_config_maps (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap]): + The list of ConfigMaps returned by a + ListUserWorkloadsConfigMapsRequest. + next_page_token (str): + The page token used to query for the next + page if one exists. + """ + + @property + def raw_page(self): + return self + + user_workloads_config_maps: MutableSequence['UserWorkloadsConfigMap'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='UserWorkloadsConfigMap', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListWorkloadsRequest(proto.Message): + r"""Request for listing workloads in a Cloud Composer + environment. + + Attributes: + parent (str): + Required. The environment name to get + workloads for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + page_size (int): + Optional. The maximum number of environments + to return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The list filter. Currently only supports equality + on the type field. The value of a field specified in the + filter expression must be one ComposerWorkloadType enum + option. It's possible to get multiple types using "OR" + operator, e.g.: "type=SCHEDULER OR type=CELERY_WORKER". If + not specified, all items are returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListWorkloadsResponse(proto.Message): + r"""Response to ListWorkloadsRequest. + + Attributes: + workloads (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse.ComposerWorkload]): + The list of environment workloads. + next_page_token (str): + The page token used to query for the next + page if one exists. + """ + class ComposerWorkloadType(proto.Enum): + r"""Supported workload types. + + Values: + COMPOSER_WORKLOAD_TYPE_UNSPECIFIED (0): + Not able to determine the type of the + workload. + CELERY_WORKER (1): + Celery worker. + KUBERNETES_WORKER (2): + Kubernetes worker. + KUBERNETES_OPERATOR_POD (3): + Workload created by Kubernetes Pod Operator. + SCHEDULER (4): + Airflow scheduler. + DAG_PROCESSOR (5): + Airflow Dag processor. + TRIGGERER (6): + Airflow triggerer. + WEB_SERVER (7): + Airflow web server UI. + REDIS (8): + Redis. + """ + COMPOSER_WORKLOAD_TYPE_UNSPECIFIED = 0 + CELERY_WORKER = 1 + KUBERNETES_WORKER = 2 + KUBERNETES_OPERATOR_POD = 3 + SCHEDULER = 4 + DAG_PROCESSOR = 5 + TRIGGERER = 6 + WEB_SERVER = 7 + REDIS = 8 + + class ComposerWorkloadState(proto.Enum): + r"""Workload states. + + Values: + COMPOSER_WORKLOAD_STATE_UNSPECIFIED (0): + Not able to determine the status of the + workload. + PENDING (1): + Workload is in pending state and has not yet + started. + OK (2): + Workload is running fine. + WARNING (3): + Workload is running but there are some + non-critical problems. + ERROR (4): + Workload is not running due to an error. + SUCCEEDED (5): + Workload has finished execution with success. + FAILED (6): + Workload has finished execution with failure. + """ + COMPOSER_WORKLOAD_STATE_UNSPECIFIED = 0 + PENDING = 1 + OK = 2 + WARNING = 3 + ERROR = 4 + SUCCEEDED = 5 + FAILED = 6 + + class ComposerWorkload(proto.Message): + r"""Information about a single workload. + + Attributes: + name (str): + Name of a workload. + type_ (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse.ComposerWorkloadType): + Type of a workload. + status (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse.ComposerWorkloadStatus): + Output only. Status of a workload. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: 'ListWorkloadsResponse.ComposerWorkloadType' = proto.Field( + proto.ENUM, + number=2, + enum='ListWorkloadsResponse.ComposerWorkloadType', + ) + status: 'ListWorkloadsResponse.ComposerWorkloadStatus' = proto.Field( + proto.MESSAGE, + number=3, + message='ListWorkloadsResponse.ComposerWorkloadStatus', + ) + + class ComposerWorkloadStatus(proto.Message): + r"""Workload status. + + Attributes: + state (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse.ComposerWorkloadState): + Output only. Workload state. + status_message (str): + Output only. Text to provide more descriptive + status. + detailed_status_message (str): + Output only. Detailed message of the status. + """ + + state: 'ListWorkloadsResponse.ComposerWorkloadState' = proto.Field( + proto.ENUM, + number=1, + enum='ListWorkloadsResponse.ComposerWorkloadState', + ) + status_message: str = proto.Field( + proto.STRING, + number=2, + ) + detailed_status_message: str = proto.Field( + proto.STRING, + number=3, + ) + + @property + def raw_page(self): + return self + + workloads: MutableSequence[ComposerWorkload] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ComposerWorkload, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SaveSnapshotRequest(proto.Message): + r"""Request to create a snapshot of a Cloud Composer environment. + + Attributes: + environment (str): + The resource name of the source environment + in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + snapshot_location (str): + Location in a Cloud Storage where the + snapshot is going to be stored, e.g.: + "gs://my-bucket/snapshots". + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + snapshot_location: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SaveSnapshotResponse(proto.Message): + r"""Response to SaveSnapshotRequest. + + Attributes: + snapshot_path (str): + The fully-resolved Cloud Storage path of the created + snapshot, e.g.: + "gs://my-bucket/snapshots/project_location_environment_timestamp". + This field is populated only if the snapshot creation was + successful. + """ + + snapshot_path: str = proto.Field( + proto.STRING, + number=1, + ) + + +class LoadSnapshotRequest(proto.Message): + r"""Request to load a snapshot into a Cloud Composer environment. + + Attributes: + environment (str): + The resource name of the target environment + in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + snapshot_path (str): + A Cloud Storage path to a snapshot to load, e.g.: + "gs://my-bucket/snapshots/project_location_environment_timestamp". + skip_pypi_packages_installation (bool): + Whether or not to skip installing Pypi + packages when loading the environment's state. + skip_environment_variables_setting (bool): + Whether or not to skip setting environment + variables when loading the environment's state. + skip_airflow_overrides_setting (bool): + Whether or not to skip setting Airflow + overrides when loading the environment's state. + skip_gcs_data_copying (bool): + Whether or not to skip copying Cloud Storage + data when loading the environment's state. + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + snapshot_path: str = proto.Field( + proto.STRING, + number=2, + ) + skip_pypi_packages_installation: bool = proto.Field( + proto.BOOL, + number=3, + ) + skip_environment_variables_setting: bool = proto.Field( + proto.BOOL, + number=4, + ) + skip_airflow_overrides_setting: bool = proto.Field( + proto.BOOL, + number=5, + ) + skip_gcs_data_copying: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class LoadSnapshotResponse(proto.Message): + r"""Response to LoadSnapshotRequest. + """ + + +class DatabaseFailoverRequest(proto.Message): + r"""Request to trigger database failover (only for highly + resilient environments). + + Attributes: + environment (str): + Target environment: + + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DatabaseFailoverResponse(proto.Message): + r"""Response for DatabaseFailoverRequest. + """ + + +class FetchDatabasePropertiesRequest(proto.Message): + r"""Request to fetch properties of environment's database. + + Attributes: + environment (str): + Required. The resource name of the + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FetchDatabasePropertiesResponse(proto.Message): + r"""Response for FetchDatabasePropertiesRequest. + + Attributes: + primary_gce_zone (str): + The Compute Engine zone that the instance is + currently serving from. + secondary_gce_zone (str): + The Compute Engine zone that the failover + instance is currently serving from for a + regional Cloud SQL instance. + is_failover_replica_available (bool): + The availability status of the failover + replica. A false status indicates that the + failover replica is out of sync. The primary + instance can only fail over to the failover + replica when the status is true. + """ + + primary_gce_zone: str = proto.Field( + proto.STRING, + number=1, + ) + secondary_gce_zone: str = proto.Field( + proto.STRING, + number=2, + ) + is_failover_replica_available: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class StorageConfig(proto.Message): + r"""The configuration for data storage in the environment. + + Attributes: + bucket (str): + Optional. The name of the Cloud Storage bucket used by the + environment. No ``gs://`` prefix. + """ + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EnvironmentConfig(proto.Message): + r"""Configuration information for an environment. + + Attributes: + gke_cluster (str): + Output only. The Kubernetes Engine cluster + used to run this environment. + dag_gcs_prefix (str): + Output only. The Cloud Storage prefix of the + DAGs for this environment. Although Cloud + Storage objects reside in a flat namespace, a + hierarchical file tree can be simulated using + "/"-delimited object name prefixes. DAG objects + for this environment reside in a simulated + directory with the given prefix. + node_count (int): + The number of nodes in the Kubernetes Engine cluster that + will be used to run this environment. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + software_config (google.cloud.orchestration.airflow.service_v1.types.SoftwareConfig): + Optional. The configuration settings for + software inside the environment. + node_config (google.cloud.orchestration.airflow.service_v1.types.NodeConfig): + Optional. The configuration used for the + Kubernetes Engine cluster. + private_environment_config (google.cloud.orchestration.airflow.service_v1.types.PrivateEnvironmentConfig): + Optional. The configuration used for the + Private IP Cloud Composer environment. + web_server_network_access_control (google.cloud.orchestration.airflow.service_v1.types.WebServerNetworkAccessControl): + Optional. The network-level access control + policy for the Airflow web server. If + unspecified, no network-level access + restrictions will be applied. + database_config (google.cloud.orchestration.airflow.service_v1.types.DatabaseConfig): + Optional. The configuration settings for + Cloud SQL instance used internally by Apache + Airflow software. + web_server_config (google.cloud.orchestration.airflow.service_v1.types.WebServerConfig): + Optional. The configuration settings for the + Airflow web server App Engine instance. + encryption_config (google.cloud.orchestration.airflow.service_v1.types.EncryptionConfig): + Optional. The encryption options for the + Cloud Composer environment and its dependencies. + Cannot be updated. + maintenance_window (google.cloud.orchestration.airflow.service_v1.types.MaintenanceWindow): + Optional. The maintenance window is the + period when Cloud Composer components may + undergo maintenance. It is defined so that + maintenance is not executed during peak hours or + critical time periods. + + The system will not be under maintenance for + every occurrence of this window, but when + maintenance is planned, it will be scheduled + during the window. + + The maintenance window period must encompass at + least 12 hours per week. This may be split into + multiple chunks, each with a size of at least 4 + hours. + + If this value is omitted, the default value for + maintenance window is applied. By default, + maintenance windows are from 00:00:00 to + 04:00:00 (GMT) on Friday, Saturday, and Sunday + every week. + workloads_config (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig): + Optional. The workloads configuration settings for the GKE + cluster associated with the Cloud Composer environment. The + GKE cluster runs Airflow scheduler, web server and workers + workloads. + + This field is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + environment_size (google.cloud.orchestration.airflow.service_v1.types.EnvironmentConfig.EnvironmentSize): + Optional. The size of the Cloud Composer environment. + + This field is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + airflow_uri (str): + Output only. The URI of the Apache Airflow Web UI hosted + within this environment (see `Airflow web + interface `__). + airflow_byoid_uri (str): + Output only. The 'bring your own identity' variant of the + URI of the Apache Airflow Web UI hosted within this + environment, to be accessed with external identities using + workforce identity federation (see `Access environments with + workforce identity + federation `__). + master_authorized_networks_config (google.cloud.orchestration.airflow.service_v1.types.MasterAuthorizedNetworksConfig): + Optional. The configuration options for GKE + cluster master authorized networks. By default + master authorized networks feature is: + + - in case of private environment: enabled with + no external networks allowlisted. + - in case of public environment: disabled. + recovery_config (google.cloud.orchestration.airflow.service_v1.types.RecoveryConfig): + Optional. The Recovery settings configuration of an + environment. + + This field is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + resilience_mode (google.cloud.orchestration.airflow.service_v1.types.EnvironmentConfig.ResilienceMode): + Optional. Resilience mode of the Cloud Composer Environment. + + This field is supported for Cloud Composer environments in + versions composer-2.2.0-airflow-\ *.*.\* and newer. + data_retention_config (google.cloud.orchestration.airflow.service_v1.types.DataRetentionConfig): + Optional. The configuration setting for + Airflow database data retention mechanism. + """ + class EnvironmentSize(proto.Enum): + r"""The size of the Cloud Composer environment. + + Values: + ENVIRONMENT_SIZE_UNSPECIFIED (0): + The size of the environment is unspecified. + ENVIRONMENT_SIZE_SMALL (1): + The environment size is small. + ENVIRONMENT_SIZE_MEDIUM (2): + The environment size is medium. + ENVIRONMENT_SIZE_LARGE (3): + The environment size is large. + """ + ENVIRONMENT_SIZE_UNSPECIFIED = 0 + ENVIRONMENT_SIZE_SMALL = 1 + ENVIRONMENT_SIZE_MEDIUM = 2 + ENVIRONMENT_SIZE_LARGE = 3 + + class ResilienceMode(proto.Enum): + r"""Resilience mode of the Cloud Composer Environment. + + Values: + RESILIENCE_MODE_UNSPECIFIED (0): + Default mode doesn't change environment + parameters. + HIGH_RESILIENCE (1): + Enabled High Resilience mode, including Cloud + SQL HA. + """ + RESILIENCE_MODE_UNSPECIFIED = 0 + HIGH_RESILIENCE = 1 + + gke_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + dag_gcs_prefix: str = proto.Field( + proto.STRING, + number=2, + ) + node_count: int = proto.Field( + proto.INT32, + number=3, + ) + software_config: 'SoftwareConfig' = proto.Field( + proto.MESSAGE, + number=4, + message='SoftwareConfig', + ) + node_config: 'NodeConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='NodeConfig', + ) + private_environment_config: 'PrivateEnvironmentConfig' = proto.Field( + proto.MESSAGE, + number=7, + message='PrivateEnvironmentConfig', + ) + web_server_network_access_control: 'WebServerNetworkAccessControl' = proto.Field( + proto.MESSAGE, + number=8, + message='WebServerNetworkAccessControl', + ) + database_config: 'DatabaseConfig' = proto.Field( + proto.MESSAGE, + number=9, + message='DatabaseConfig', + ) + web_server_config: 'WebServerConfig' = proto.Field( + proto.MESSAGE, + number=10, + message='WebServerConfig', + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=11, + message='EncryptionConfig', + ) + maintenance_window: 'MaintenanceWindow' = proto.Field( + proto.MESSAGE, + number=12, + message='MaintenanceWindow', + ) + workloads_config: 'WorkloadsConfig' = proto.Field( + proto.MESSAGE, + number=15, + message='WorkloadsConfig', + ) + environment_size: EnvironmentSize = proto.Field( + proto.ENUM, + number=16, + enum=EnvironmentSize, + ) + airflow_uri: str = proto.Field( + proto.STRING, + number=6, + ) + airflow_byoid_uri: str = proto.Field( + proto.STRING, + number=20, + ) + master_authorized_networks_config: 'MasterAuthorizedNetworksConfig' = proto.Field( + proto.MESSAGE, + number=17, + message='MasterAuthorizedNetworksConfig', + ) + recovery_config: 'RecoveryConfig' = proto.Field( + proto.MESSAGE, + number=18, + message='RecoveryConfig', + ) + resilience_mode: ResilienceMode = proto.Field( + proto.ENUM, + number=19, + enum=ResilienceMode, + ) + data_retention_config: 'DataRetentionConfig' = proto.Field( + proto.MESSAGE, + number=21, + message='DataRetentionConfig', + ) + + +class WebServerNetworkAccessControl(proto.Message): + r"""Network-level access control policy for the Airflow web + server. + + Attributes: + allowed_ip_ranges (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.WebServerNetworkAccessControl.AllowedIpRange]): + A collection of allowed IP ranges with + descriptions. + """ + + class AllowedIpRange(proto.Message): + r"""Allowed IP range with user-provided description. + + Attributes: + value (str): + IP address or range, defined using CIDR notation, of + requests that this rule applies to. Examples: + ``192.168.1.1`` or ``192.168.0.0/16`` or ``2001:db8::/32`` + or ``2001:0db8:0000:0042:0000:8a2e:0370:7334``. + + IP range prefixes should be properly truncated. For example, + ``1.2.3.4/24`` should be truncated to ``1.2.3.0/24``. + Similarly, for IPv6, ``2001:db8::1/32`` should be truncated + to ``2001:db8::/32``. + description (str): + Optional. User-provided description. It must + contain at most 300 characters. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + + allowed_ip_ranges: MutableSequence[AllowedIpRange] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AllowedIpRange, + ) + + +class DatabaseConfig(proto.Message): + r"""The configuration of Cloud SQL instance that is used by the + Apache Airflow software. + + Attributes: + machine_type (str): + Optional. Cloud SQL machine type used by Airflow database. + It has to be one of: db-n1-standard-2, db-n1-standard-4, + db-n1-standard-8 or db-n1-standard-16. If not specified, + db-n1-standard-2 will be used. Supported for Cloud Composer + environments in versions composer-1.\ *.*-airflow-*.*.*. + zone (str): + Optional. The Compute Engine zone where the Airflow database + is created. If zone is provided, it must be in the region + selected for the environment. If zone is not provided, a + zone is automatically selected. The zone can only be set + during environment creation. Supported for Cloud Composer + environments in versions composer-2.\ *.*-airflow-*.*.*. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + zone: str = proto.Field( + proto.STRING, + number=2, + ) + + +class WebServerConfig(proto.Message): + r"""The configuration settings for the Airflow web server App Engine + instance. Supported for Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.\* + + Attributes: + machine_type (str): + Optional. Machine type on which Airflow web + server is running. It has to be one of: + composer-n1-webserver-2, composer-n1-webserver-4 + or composer-n1-webserver-8. + If not specified, composer-n1-webserver-2 will + be used. Value custom is returned only in + response, if Airflow web server parameters were + manually changed to a non-standard values. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EncryptionConfig(proto.Message): + r"""The encryption options for the Cloud Composer environment and its + dependencies.Supported for Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + Attributes: + kms_key_name (str): + Optional. Customer-managed Encryption Key + available through Google's Key Management + Service. Cannot be updated. If not specified, + Google-managed key will be used. + """ + + kms_key_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class MaintenanceWindow(proto.Message): + r"""The configuration settings for Cloud Composer maintenance window. + The following example: + + :: + + { + "startTime":"2019-08-01T01:00:00Z" + "endTime":"2019-08-01T07:00:00Z" + "recurrence":"FREQ=WEEKLY;BYDAY=TU,WE" + } + + would define a maintenance window between 01 and 07 hours UTC during + each Tuesday and Wednesday. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Start time of the first recurrence + of the maintenance window. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Maintenance window end time. It is used only to + calculate the duration of the maintenance window. The value + for end-time must be in the future, relative to + ``start_time``. + recurrence (str): + Required. Maintenance window recurrence. Format is a subset + of `RFC-5545 `__ + ``RRULE``. The only allowed values for ``FREQ`` field are + ``FREQ=DAILY`` and ``FREQ=WEEKLY;BYDAY=...`` Example values: + ``FREQ=WEEKLY;BYDAY=TU,WE``, ``FREQ=DAILY``. + """ + + start_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, + ) + recurrence: str = proto.Field( + proto.STRING, + number=3, + ) + + +class SoftwareConfig(proto.Message): + r"""Specifies the selection and configuration of software inside + the environment. + + Attributes: + image_version (str): + Optional. The version of the software running in the + environment. This encapsulates both the version of Cloud + Composer functionality and the version of Apache Airflow. It + must match the regular expression + ``composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)``. + When used as input, the server also checks if the provided + version is supported and denies the request for an + unsupported version. + + The Cloud Composer portion of the image version is a full + `semantic version `__, or an alias in + the form of major version number or ``latest``. When an + alias is provided, the server replaces it with the current + Cloud Composer version that satisfies the alias. + + The Apache Airflow portion of the image version is a full + semantic version that points to one of the supported Apache + Airflow versions, or an alias in the form of only major or + major.minor versions specified. When an alias is provided, + the server replaces it with the latest Apache Airflow + version that satisfies the alias and is supported in the + given Cloud Composer version. + + In all cases, the resolved image version is stored in the + same field. + + See also `version + list `__ + and `versioning + overview `__. + airflow_config_overrides (MutableMapping[str, str]): + Optional. Apache Airflow configuration properties to + override. + + Property keys contain the section and property names, + separated by a hyphen, for example + "core-dags_are_paused_at_creation". Section names must not + contain hyphens ("-"), opening square brackets ("["), or + closing square brackets ("]"). The property name must not be + empty and must not contain an equals sign ("=") or semicolon + (";"). Section and property names must not contain a period + ("."). Apache Airflow configuration property names must be + written in + `snake_case `__. + Property values can contain any character, and can be + written in any lower/upper case format. + + Certain Apache Airflow configuration property values are + `blocked `__, + and cannot be overridden. + pypi_packages (MutableMapping[str, str]): + Optional. Custom Python Package Index (PyPI) packages to be + installed in the environment. + + Keys refer to the lowercase package name such as "numpy" and + values are the lowercase extras and version specifier such + as "==1.12.0", "[devel,gcp_api]", or "[devel]>=1.8.2, + <1.9.2". To specify a package without pinning it to a + version specifier, use the empty string as the value. + env_variables (MutableMapping[str, str]): + Optional. Additional environment variables to provide to the + Apache Airflow scheduler, worker, and webserver processes. + + Environment variable names must match the regular expression + ``[a-zA-Z_][a-zA-Z0-9_]*``. They cannot specify Apache + Airflow software configuration overrides (they cannot match + the regular expression ``AIRFLOW__[A-Z0-9_]+__[A-Z0-9_]+``), + and they cannot match any of the following reserved names: + + - ``AIRFLOW_HOME`` + - ``C_FORCE_ROOT`` + - ``CONTAINER_NAME`` + - ``DAGS_FOLDER`` + - ``GCP_PROJECT`` + - ``GCS_BUCKET`` + - ``GKE_CLUSTER_NAME`` + - ``SQL_DATABASE`` + - ``SQL_INSTANCE`` + - ``SQL_PASSWORD`` + - ``SQL_PROJECT`` + - ``SQL_REGION`` + - ``SQL_USER`` + python_version (str): + Optional. The major version of Python used to run the Apache + Airflow scheduler, worker, and webserver processes. + + Can be set to '2' or '3'. If not specified, the default is + '3'. Cannot be updated. + + This field is only supported for Cloud Composer environments + in versions composer-1.\ *.*-airflow-*.*.*. Environments in + newer versions always use Python major version 3. + scheduler_count (int): + Optional. The number of schedulers for Airflow. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-2.*.*. + cloud_data_lineage_integration (google.cloud.orchestration.airflow.service_v1.types.CloudDataLineageIntegration): + Optional. The configuration for Cloud Data + Lineage integration. + web_server_plugins_mode (google.cloud.orchestration.airflow.service_v1.types.SoftwareConfig.WebServerPluginsMode): + Optional. Whether or not the web server uses custom plugins. + If unspecified, the field defaults to ``PLUGINS_ENABLED``. + + This field is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + """ + class WebServerPluginsMode(proto.Enum): + r"""Web server plugins mode of the Cloud Composer environment. + + Values: + WEB_SERVER_PLUGINS_MODE_UNSPECIFIED (0): + Default mode. + PLUGINS_DISABLED (1): + Web server plugins are not supported. + PLUGINS_ENABLED (2): + Web server plugins are supported. + """ + WEB_SERVER_PLUGINS_MODE_UNSPECIFIED = 0 + PLUGINS_DISABLED = 1 + PLUGINS_ENABLED = 2 + + image_version: str = proto.Field( + proto.STRING, + number=1, + ) + airflow_config_overrides: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + pypi_packages: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + env_variables: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + python_version: str = proto.Field( + proto.STRING, + number=6, + ) + scheduler_count: int = proto.Field( + proto.INT32, + number=7, + ) + cloud_data_lineage_integration: 'CloudDataLineageIntegration' = proto.Field( + proto.MESSAGE, + number=8, + message='CloudDataLineageIntegration', + ) + web_server_plugins_mode: WebServerPluginsMode = proto.Field( + proto.ENUM, + number=10, + enum=WebServerPluginsMode, + ) + + +class IPAllocationPolicy(proto.Message): + r"""Configuration for controlling how IPs are allocated in the + GKE cluster running the Apache Airflow software. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + use_ip_aliases (bool): + Optional. Whether or not to enable Alias IPs in the GKE + cluster. If ``true``, a VPC-native cluster is created. + + This field is only supported for Cloud Composer environments + in versions composer-1.\ *.*-airflow-*.*.*. Environments in + newer versions always use VPC-native GKE clusters. + cluster_secondary_range_name (str): + Optional. The name of the GKE cluster's secondary range used + to allocate IP addresses to pods. + + For Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*, this field is applicable + only when ``use_ip_aliases`` is true. + + This field is a member of `oneof`_ ``cluster_ip_allocation``. + cluster_ipv4_cidr_block (str): + Optional. The IP address range used to allocate IP addresses + to pods in the GKE cluster. + + For Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*, this field is applicable + only when ``use_ip_aliases`` is true. + + Set to blank to have GKE choose a range with the default + size. + + Set to /netmask (e.g. ``/14``) to have GKE choose a range + with a specific netmask. + + Set to a + `CIDR `__ + notation (e.g. ``10.96.0.0/14``) from the RFC-1918 private + networks (e.g. ``10.0.0.0/8``, ``172.16.0.0/12``, + ``192.168.0.0/16``) to pick a specific range to use. + + This field is a member of `oneof`_ ``cluster_ip_allocation``. + services_secondary_range_name (str): + Optional. The name of the services' secondary range used to + allocate IP addresses to the GKE cluster. + + For Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*, this field is applicable + only when ``use_ip_aliases`` is true. + + This field is a member of `oneof`_ ``services_ip_allocation``. + services_ipv4_cidr_block (str): + Optional. The IP address range of the services IP addresses + in this GKE cluster. + + For Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*, this field is applicable + only when ``use_ip_aliases`` is true. + + Set to blank to have GKE choose a range with the default + size. + + Set to /netmask (e.g. ``/14``) to have GKE choose a range + with a specific netmask. + + Set to a + `CIDR `__ + notation (e.g. ``10.96.0.0/14``) from the RFC-1918 private + networks (e.g. ``10.0.0.0/8``, ``172.16.0.0/12``, + ``192.168.0.0/16``) to pick a specific range to use. + + This field is a member of `oneof`_ ``services_ip_allocation``. + """ + + use_ip_aliases: bool = proto.Field( + proto.BOOL, + number=1, + ) + cluster_secondary_range_name: str = proto.Field( + proto.STRING, + number=2, + oneof='cluster_ip_allocation', + ) + cluster_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=4, + oneof='cluster_ip_allocation', + ) + services_secondary_range_name: str = proto.Field( + proto.STRING, + number=3, + oneof='services_ip_allocation', + ) + services_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=5, + oneof='services_ip_allocation', + ) + + +class NodeConfig(proto.Message): + r"""The configuration information for the Kubernetes Engine nodes + running the Apache Airflow software. + + Attributes: + location (str): + Optional. The Compute Engine + `zone `__ in which to deploy + the VMs used to run the Apache Airflow software, specified + as a `relative resource + name `__. + For example: "projects/{projectId}/zones/{zoneId}". + + This ``location`` must belong to the enclosing environment's + project and location. If both this field and + ``nodeConfig.machineType`` are specified, + ``nodeConfig.machineType`` must belong to this ``location``; + if both are unspecified, the service will pick a zone in the + Compute Engine region corresponding to the Cloud Composer + location, and propagate that choice to both fields. If only + one field (``location`` or ``nodeConfig.machineType``) is + specified, the location information from the specified field + will be propagated to the unspecified field. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + machine_type (str): + Optional. The Compute Engine `machine + type `__ used for cluster + instances, specified as a `relative resource + name `__. + For example: + "projects/{projectId}/zones/{zoneId}/machineTypes/{machineTypeId}". + + The ``machineType`` must belong to the enclosing + environment's project and location. If both this field and + ``nodeConfig.location`` are specified, this ``machineType`` + must belong to the ``nodeConfig.location``; if both are + unspecified, the service will pick a zone in the Compute + Engine region corresponding to the Cloud Composer location, + and propagate that choice to both fields. If exactly one of + this field and ``nodeConfig.location`` is specified, the + location information from the specified field will be + propagated to the unspecified field. + + The ``machineTypeId`` must not be a `shared-core machine + type `__. + + If this field is unspecified, the ``machineTypeId`` defaults + to "n1-standard-1". + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + network (str): + Optional. The Compute Engine network to be used for machine + communications, specified as a `relative resource + name `__. + For example: + "projects/{projectId}/global/networks/{networkId}". + + If unspecified, the "default" network ID in the + environment's project is used. If a `Custom Subnet + Network `__ is + provided, ``nodeConfig.subnetwork`` must also be provided. + For `Shared VPC `__ subnetwork + requirements, see ``nodeConfig.subnetwork``. + subnetwork (str): + Optional. The Compute Engine subnetwork to be used for + machine communications, specified as a `relative resource + name `__. + For example: + "projects/{projectId}/regions/{regionId}/subnetworks/{subnetworkId}" + + If a subnetwork is provided, ``nodeConfig.network`` must + also be provided, and the subnetwork must belong to the + enclosing environment's project and location. + disk_size_gb (int): + Optional. The disk size in GB used for node VMs. Minimum + size is 30GB. If unspecified, defaults to 100GB. Cannot be + updated. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + oauth_scopes (MutableSequence[str]): + Optional. The set of Google API scopes to be made available + on all node VMs. If ``oauth_scopes`` is empty, defaults to + ["https://www.googleapis.com/auth/cloud-platform"]. Cannot + be updated. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + service_account (str): + Optional. The Google Cloud Platform Service + Account to be used by the node VMs. If a service + account is not specified, the "default" Compute + Engine service account is used. Cannot be + updated. + tags (MutableSequence[str]): + Optional. The list of instance tags applied to all node VMs. + Tags are used to identify valid sources or targets for + network firewalls. Each tag within the list must comply with + `RFC1035 `__. Cannot + be updated. + ip_allocation_policy (google.cloud.orchestration.airflow.service_v1.types.IPAllocationPolicy): + Optional. The configuration for controlling + how IPs are allocated in the GKE cluster. + enable_ip_masq_agent (bool): + Optional. Deploys 'ip-masq-agent' daemon set + in the GKE cluster and defines + nonMasqueradeCIDRs equals to pod IP range so IP + masquerading is used for all destination + addresses, except between pods traffic. + + See: + + https://cloud.google.com/kubernetes-engine/docs/how-to/ip-masquerade-agent + composer_network_attachment (str): + Optional. Network Attachment that Cloud Composer environment + is connected to, which provides connectivity with a user's + VPC network. Takes precedence over network and subnetwork + settings. If not provided, but network and subnetwork are + defined during environment, it will be provisioned. If not + provided and network and subnetwork are also empty, then + connectivity to user's VPC network is disabled. Network + attachment must be provided in format + projects/{project}/regions/{region}/networkAttachments/{networkAttachment}. + + This field is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + composer_internal_ipv4_cidr_block (str): + Optional. The IP range in CIDR notation to use internally by + Cloud Composer. IP addresses are not reserved - and the same + range can be used by multiple Cloud Composer environments. + In case of overlap, IPs from this range will not be + accessible in the user's VPC network. Cannot be updated. If + not specified, the default value of '100.64.128.0/20' is + used. + + This field is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + """ + + location: str = proto.Field( + proto.STRING, + number=1, + ) + machine_type: str = proto.Field( + proto.STRING, + number=2, + ) + network: str = proto.Field( + proto.STRING, + number=3, + ) + subnetwork: str = proto.Field( + proto.STRING, + number=4, + ) + disk_size_gb: int = proto.Field( + proto.INT32, + number=5, + ) + oauth_scopes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + service_account: str = proto.Field( + proto.STRING, + number=7, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + ip_allocation_policy: 'IPAllocationPolicy' = proto.Field( + proto.MESSAGE, + number=9, + message='IPAllocationPolicy', + ) + enable_ip_masq_agent: bool = proto.Field( + proto.BOOL, + number=11, + ) + composer_network_attachment: str = proto.Field( + proto.STRING, + number=12, + ) + composer_internal_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=13, + ) + + +class PrivateClusterConfig(proto.Message): + r"""Configuration options for the private GKE cluster in a Cloud + Composer environment. + + Attributes: + enable_private_endpoint (bool): + Optional. If ``true``, access to the public endpoint of the + GKE cluster is denied. + master_ipv4_cidr_block (str): + Optional. The CIDR block from which IPv4 + range for GKE master will be reserved. If left + blank, the default value of '172.16.0.0/23' is + used. + master_ipv4_reserved_range (str): + Output only. The IP range in CIDR notation to + use for the hosted master network. This range is + used for assigning internal IP addresses to the + GKE cluster master or set of masters and to the + internal load balancer virtual IP. This range + must not overlap with any other ranges in use + within the cluster's network. + """ + + enable_private_endpoint: bool = proto.Field( + proto.BOOL, + number=1, + ) + master_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=2, + ) + master_ipv4_reserved_range: str = proto.Field( + proto.STRING, + number=3, + ) + + +class NetworkingConfig(proto.Message): + r"""Configuration options for networking connections in the + Composer 2 environment. + + Attributes: + connection_type (google.cloud.orchestration.airflow.service_v1.types.NetworkingConfig.ConnectionType): + Optional. Indicates the user requested + specifc connection type between Tenant and + Customer projects. You cannot set networking + connection type in public IP environment. + """ + class ConnectionType(proto.Enum): + r"""Represents connection type between Composer environment in + Customer Project and the corresponding Tenant project, from a + predefined list of available connection modes. + + Values: + CONNECTION_TYPE_UNSPECIFIED (0): + No specific connection type was requested, so + the environment uses the default value + corresponding to the rest of its configuration. + VPC_PEERING (1): + Requests the use of VPC peerings for + connecting the Customer and Tenant projects. + PRIVATE_SERVICE_CONNECT (2): + Requests the use of Private Service Connect + for connecting the Customer and Tenant projects. + """ + CONNECTION_TYPE_UNSPECIFIED = 0 + VPC_PEERING = 1 + PRIVATE_SERVICE_CONNECT = 2 + + connection_type: ConnectionType = proto.Field( + proto.ENUM, + number=1, + enum=ConnectionType, + ) + + +class PrivateEnvironmentConfig(proto.Message): + r"""The configuration information for configuring a Private IP + Cloud Composer environment. + + Attributes: + enable_private_environment (bool): + Optional. If ``true``, a Private IP Cloud Composer + environment is created. If this field is set to true, + ``IPAllocationPolicy.use_ip_aliases`` must be set to true + for Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + enable_private_builds_only (bool): + Optional. If ``true``, builds performed during operations + that install Python packages have only private connectivity + to Google services (including Artifact Registry) and VPC + network (if either ``NodeConfig.network`` and + ``NodeConfig.subnetwork`` fields or + ``NodeConfig.composer_network_attachment`` field are + specified). If ``false``, the builds also have access to the + internet. + + This field is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + private_cluster_config (google.cloud.orchestration.airflow.service_v1.types.PrivateClusterConfig): + Optional. Configuration for the private GKE + cluster for a Private IP Cloud Composer + environment. + web_server_ipv4_cidr_block (str): + Optional. The CIDR block from which IP range for web server + will be reserved. Needs to be disjoint from + ``private_cluster_config.master_ipv4_cidr_block`` and + ``cloud_sql_ipv4_cidr_block``. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + cloud_sql_ipv4_cidr_block (str): + Optional. The CIDR block from which IP range in tenant + project will be reserved for Cloud SQL. Needs to be disjoint + from ``web_server_ipv4_cidr_block``. + web_server_ipv4_reserved_range (str): + Output only. The IP range reserved for the tenant project's + App Engine VMs. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + cloud_composer_network_ipv4_cidr_block (str): + Optional. The CIDR block from which IP range for Cloud + Composer Network in tenant project will be reserved. Needs + to be disjoint from + private_cluster_config.master_ipv4_cidr_block and + cloud_sql_ipv4_cidr_block. + + This field is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + cloud_composer_network_ipv4_reserved_range (str): + Output only. The IP range reserved for the tenant project's + Cloud Composer network. + + This field is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + enable_privately_used_public_ips (bool): + Optional. When enabled, IPs from public (non-RFC1918) ranges + can be used for + ``IPAllocationPolicy.cluster_ipv4_cidr_block`` and + ``IPAllocationPolicy.service_ipv4_cidr_block``. + cloud_composer_connection_subnetwork (str): + Optional. When specified, the environment + will use Private Service Connect instead of VPC + peerings to connect to Cloud SQL in the Tenant + Project, and the PSC endpoint in the Customer + Project will use an IP address from this + subnetwork. + networking_config (google.cloud.orchestration.airflow.service_v1.types.NetworkingConfig): + Optional. Configuration for the network + connections configuration in the environment. + """ + + enable_private_environment: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_private_builds_only: bool = proto.Field( + proto.BOOL, + number=11, + ) + private_cluster_config: 'PrivateClusterConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='PrivateClusterConfig', + ) + web_server_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=3, + ) + cloud_sql_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=4, + ) + web_server_ipv4_reserved_range: str = proto.Field( + proto.STRING, + number=5, + ) + cloud_composer_network_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=7, + ) + cloud_composer_network_ipv4_reserved_range: str = proto.Field( + proto.STRING, + number=8, + ) + enable_privately_used_public_ips: bool = proto.Field( + proto.BOOL, + number=6, + ) + cloud_composer_connection_subnetwork: str = proto.Field( + proto.STRING, + number=9, + ) + networking_config: 'NetworkingConfig' = proto.Field( + proto.MESSAGE, + number=10, + message='NetworkingConfig', + ) + + +class WorkloadsConfig(proto.Message): + r"""The Kubernetes workloads configuration for GKE cluster associated + with the Cloud Composer environment. Supported for Cloud Composer + environments in versions composer-2.\ *.*-airflow-*.*.\* and newer. + + Attributes: + scheduler (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig.SchedulerResource): + Optional. Resources used by Airflow + schedulers. + web_server (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig.WebServerResource): + Optional. Resources used by Airflow web + server. + worker (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig.WorkerResource): + Optional. Resources used by Airflow workers. + triggerer (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig.TriggererResource): + Optional. Resources used by Airflow + triggerers. + dag_processor (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig.DagProcessorResource): + Optional. Resources used by Airflow DAG processors. + + This field is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + """ + + class SchedulerResource(proto.Message): + r"""Configuration for resources used by Airflow schedulers. + + Attributes: + cpu (float): + Optional. CPU request and limit for a single + Airflow scheduler replica. + memory_gb (float): + Optional. Memory (GB) request and limit for a + single Airflow scheduler replica. + storage_gb (float): + Optional. Storage (GB) request and limit for + a single Airflow scheduler replica. + count (int): + Optional. The number of schedulers. + """ + + cpu: float = proto.Field( + proto.FLOAT, + number=1, + ) + memory_gb: float = proto.Field( + proto.FLOAT, + number=2, + ) + storage_gb: float = proto.Field( + proto.FLOAT, + number=3, + ) + count: int = proto.Field( + proto.INT32, + number=4, + ) + + class WebServerResource(proto.Message): + r"""Configuration for resources used by Airflow web server. + + Attributes: + cpu (float): + Optional. CPU request and limit for Airflow + web server. + memory_gb (float): + Optional. Memory (GB) request and limit for + Airflow web server. + storage_gb (float): + Optional. Storage (GB) request and limit for + Airflow web server. + """ + + cpu: float = proto.Field( + proto.FLOAT, + number=1, + ) + memory_gb: float = proto.Field( + proto.FLOAT, + number=2, + ) + storage_gb: float = proto.Field( + proto.FLOAT, + number=3, + ) + + class WorkerResource(proto.Message): + r"""Configuration for resources used by Airflow workers. + + Attributes: + cpu (float): + Optional. CPU request and limit for a single + Airflow worker replica. + memory_gb (float): + Optional. Memory (GB) request and limit for a + single Airflow worker replica. + storage_gb (float): + Optional. Storage (GB) request and limit for + a single Airflow worker replica. + min_count (int): + Optional. Minimum number of workers for + autoscaling. + max_count (int): + Optional. Maximum number of workers for + autoscaling. + """ + + cpu: float = proto.Field( + proto.FLOAT, + number=1, + ) + memory_gb: float = proto.Field( + proto.FLOAT, + number=2, + ) + storage_gb: float = proto.Field( + proto.FLOAT, + number=3, + ) + min_count: int = proto.Field( + proto.INT32, + number=4, + ) + max_count: int = proto.Field( + proto.INT32, + number=5, + ) + + class TriggererResource(proto.Message): + r"""Configuration for resources used by Airflow triggerers. + + Attributes: + count (int): + Optional. The number of triggerers. + cpu (float): + Optional. CPU request and limit for a single + Airflow triggerer replica. + memory_gb (float): + Optional. Memory (GB) request and limit for a + single Airflow triggerer replica. + """ + + count: int = proto.Field( + proto.INT32, + number=1, + ) + cpu: float = proto.Field( + proto.FLOAT, + number=2, + ) + memory_gb: float = proto.Field( + proto.FLOAT, + number=3, + ) + + class DagProcessorResource(proto.Message): + r"""Configuration for resources used by Airflow DAG processors. + + This field is supported for Cloud Composer environments in versions + composer-3-airflow-\ *.*.\ *-build.* and newer. + + Attributes: + cpu (float): + Optional. CPU request and limit for a single + Airflow DAG processor replica. + memory_gb (float): + Optional. Memory (GB) request and limit for a + single Airflow DAG processor replica. + storage_gb (float): + Optional. Storage (GB) request and limit for + a single Airflow DAG processor replica. + count (int): + Optional. The number of DAG processors. If + not provided or set to 0, a single DAG processor + instance will be created. + """ + + cpu: float = proto.Field( + proto.FLOAT, + number=1, + ) + memory_gb: float = proto.Field( + proto.FLOAT, + number=2, + ) + storage_gb: float = proto.Field( + proto.FLOAT, + number=3, + ) + count: int = proto.Field( + proto.INT32, + number=4, + ) + + scheduler: SchedulerResource = proto.Field( + proto.MESSAGE, + number=1, + message=SchedulerResource, + ) + web_server: WebServerResource = proto.Field( + proto.MESSAGE, + number=2, + message=WebServerResource, + ) + worker: WorkerResource = proto.Field( + proto.MESSAGE, + number=3, + message=WorkerResource, + ) + triggerer: TriggererResource = proto.Field( + proto.MESSAGE, + number=4, + message=TriggererResource, + ) + dag_processor: DagProcessorResource = proto.Field( + proto.MESSAGE, + number=5, + message=DagProcessorResource, + ) + + +class RecoveryConfig(proto.Message): + r"""The Recovery settings of an environment. + + Attributes: + scheduled_snapshots_config (google.cloud.orchestration.airflow.service_v1.types.ScheduledSnapshotsConfig): + Optional. The configuration for scheduled + snapshot creation mechanism. + """ + + scheduled_snapshots_config: 'ScheduledSnapshotsConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='ScheduledSnapshotsConfig', + ) + + +class ScheduledSnapshotsConfig(proto.Message): + r"""The configuration for scheduled snapshot creation mechanism. + + Attributes: + enabled (bool): + Optional. Whether scheduled snapshots + creation is enabled. + snapshot_location (str): + Optional. The Cloud Storage location for + storing automatically created snapshots. + snapshot_creation_schedule (str): + Optional. The cron expression representing + the time when snapshots creation mechanism runs. + This field is subject to additional validation + around frequency of execution. + time_zone (str): + Optional. Time zone that sets the context to interpret + snapshot_creation_schedule. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + snapshot_location: str = proto.Field( + proto.STRING, + number=6, + ) + snapshot_creation_schedule: str = proto.Field( + proto.STRING, + number=3, + ) + time_zone: str = proto.Field( + proto.STRING, + number=5, + ) + + +class MasterAuthorizedNetworksConfig(proto.Message): + r"""Configuration options for the master authorized networks + feature. Enabled master authorized networks will disallow all + external traffic to access Kubernetes master through HTTPS + except traffic from the given CIDR blocks, Google Compute Engine + Public IPs and Google Prod IPs. + + Attributes: + enabled (bool): + Whether or not master authorized networks + feature is enabled. + cidr_blocks (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.MasterAuthorizedNetworksConfig.CidrBlock]): + Up to 50 external networks that could access + Kubernetes master through HTTPS. + """ + + class CidrBlock(proto.Message): + r"""CIDR block with an optional name. + + Attributes: + display_name (str): + User-defined name that identifies the CIDR + block. + cidr_block (str): + CIDR block that must be specified in CIDR + notation. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + cidr_block: str = proto.Field( + proto.STRING, + number=2, + ) + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + cidr_blocks: MutableSequence[CidrBlock] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=CidrBlock, + ) + + +class CloudDataLineageIntegration(proto.Message): + r"""Configuration for Cloud Data Lineage integration. + + Attributes: + enabled (bool): + Optional. Whether or not Cloud Data Lineage + integration is enabled. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class Environment(proto.Message): + r"""An environment for running orchestration tasks. + + Attributes: + name (str): + Identifier. The resource name of the + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + EnvironmentId must start with a lowercase letter + followed by up to 63 lowercase letters, numbers, + or hyphens, and cannot end with a hyphen. + config (google.cloud.orchestration.airflow.service_v1.types.EnvironmentConfig): + Optional. Configuration parameters for this + environment. + uuid (str): + Output only. The UUID (Universally Unique + IDentifier) associated with this environment. + This value is generated when the environment is + created. + state (google.cloud.orchestration.airflow.service_v1.types.Environment.State): + The current state of the environment. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + environment was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + environment was last modified. + labels (MutableMapping[str, str]): + Optional. User-defined labels for this environment. The + labels map can contain no more than 64 entries. Entries of + the labels map are UTF8 strings that comply with the + following restrictions: + + - Keys must conform to regexp: + [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62} + - Values must conform to regexp: + [\p{Ll}\p{Lo}\p{N}_-]{0,63} + - Both keys and values are additionally constrained to be + <= 128 bytes in size. + satisfies_pzs (bool): + Output only. Reserved for future use. + satisfies_pzi (bool): + Output only. Reserved for future use. + storage_config (google.cloud.orchestration.airflow.service_v1.types.StorageConfig): + Optional. Storage configuration for this + environment. + """ + class State(proto.Enum): + r"""State of the environment. + + Values: + STATE_UNSPECIFIED (0): + The state of the environment is unknown. + CREATING (1): + The environment is in the process of being + created. + RUNNING (2): + The environment is currently running and + healthy. It is ready for use. + UPDATING (3): + The environment is being updated. It remains + usable but cannot receive additional update + requests or be deleted at this time. + DELETING (4): + The environment is undergoing deletion. It + cannot be used. + ERROR (5): + The environment has encountered an error and + cannot be used. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + RUNNING = 2 + UPDATING = 3 + DELETING = 4 + ERROR = 5 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + config: 'EnvironmentConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='EnvironmentConfig', + ) + uuid: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=8, + ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=10, + ) + storage_config: 'StorageConfig' = proto.Field( + proto.MESSAGE, + number=9, + message='StorageConfig', + ) + + +class CheckUpgradeRequest(proto.Message): + r"""Request to check whether image upgrade will succeed. + + Attributes: + environment (str): + Required. The resource name of the + environment to check upgrade for, in the form: + + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + image_version (str): + Optional. The version of the software running in the + environment. This encapsulates both the version of Cloud + Composer functionality and the version of Apache Airflow. It + must match the regular expression + ``composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)``. + When used as input, the server also checks if the provided + version is supported and denies the request for an + unsupported version. + + The Cloud Composer portion of the image version is a full + `semantic version `__, or an alias in + the form of major version number or ``latest``. When an + alias is provided, the server replaces it with the current + Cloud Composer version that satisfies the alias. + + The Apache Airflow portion of the image version is a full + semantic version that points to one of the supported Apache + Airflow versions, or an alias in the form of only major or + major.minor versions specified. When an alias is provided, + the server replaces it with the latest Apache Airflow + version that satisfies the alias and is supported in the + given Cloud Composer version. + + In all cases, the resolved image version is stored in the + same field. + + See also `version + list `__ + and `versioning + overview `__. + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + image_version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CheckUpgradeResponse(proto.Message): + r"""Message containing information about the result of an upgrade + check operation. + + Attributes: + build_log_uri (str): + Output only. Url for a docker build log of an + upgraded image. + contains_pypi_modules_conflict (google.cloud.orchestration.airflow.service_v1.types.CheckUpgradeResponse.ConflictResult): + Output only. Whether build has succeeded or + failed on modules conflicts. + pypi_conflict_build_log_extract (str): + Output only. Extract from a docker image + build log containing information about pypi + modules conflicts. + image_version (str): + Composer image for which the build was + happening. + pypi_dependencies (MutableMapping[str, str]): + Pypi dependencies specified in the + environment configuration, at the time when the + build was triggered. + """ + class ConflictResult(proto.Enum): + r"""Whether there were python modules conflict during image + build. + + Values: + CONFLICT_RESULT_UNSPECIFIED (0): + It is unknown whether build had conflicts or + not. + CONFLICT (1): + There were python packages conflicts. + NO_CONFLICT (2): + There were no python packages conflicts. + """ + CONFLICT_RESULT_UNSPECIFIED = 0 + CONFLICT = 1 + NO_CONFLICT = 2 + + build_log_uri: str = proto.Field( + proto.STRING, + number=1, + ) + contains_pypi_modules_conflict: ConflictResult = proto.Field( + proto.ENUM, + number=4, + enum=ConflictResult, + ) + pypi_conflict_build_log_extract: str = proto.Field( + proto.STRING, + number=3, + ) + image_version: str = proto.Field( + proto.STRING, + number=5, + ) + pypi_dependencies: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + + +class DataRetentionConfig(proto.Message): + r"""The configuration setting for Airflow database data retention + mechanism. + + Attributes: + airflow_metadata_retention_config (google.cloud.orchestration.airflow.service_v1.types.AirflowMetadataRetentionPolicyConfig): + Optional. The retention policy for airflow + metadata database. + task_logs_retention_config (google.cloud.orchestration.airflow.service_v1.types.TaskLogsRetentionConfig): + Optional. The configuration settings for task + logs retention + """ + + airflow_metadata_retention_config: 'AirflowMetadataRetentionPolicyConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='AirflowMetadataRetentionPolicyConfig', + ) + task_logs_retention_config: 'TaskLogsRetentionConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='TaskLogsRetentionConfig', + ) + + +class TaskLogsRetentionConfig(proto.Message): + r"""The configuration setting for Task Logs. + + Attributes: + storage_mode (google.cloud.orchestration.airflow.service_v1.types.TaskLogsRetentionConfig.TaskLogsStorageMode): + Optional. The mode of storage for Airflow + workers task logs. + """ + class TaskLogsStorageMode(proto.Enum): + r"""The definition of task_logs_storage_mode. + + Values: + TASK_LOGS_STORAGE_MODE_UNSPECIFIED (0): + This configuration is not specified by the + user. + CLOUD_LOGGING_AND_CLOUD_STORAGE (1): + Store task logs in Cloud Logging and in the + environment's Cloud Storage bucket. + CLOUD_LOGGING_ONLY (2): + Store task logs in Cloud Logging only. + """ + TASK_LOGS_STORAGE_MODE_UNSPECIFIED = 0 + CLOUD_LOGGING_AND_CLOUD_STORAGE = 1 + CLOUD_LOGGING_ONLY = 2 + + storage_mode: TaskLogsStorageMode = proto.Field( + proto.ENUM, + number=2, + enum=TaskLogsStorageMode, + ) + + +class AirflowMetadataRetentionPolicyConfig(proto.Message): + r"""The policy for airflow metadata database retention. + + Attributes: + retention_mode (google.cloud.orchestration.airflow.service_v1.types.AirflowMetadataRetentionPolicyConfig.RetentionMode): + Optional. Retention can be either enabled or + disabled. + retention_days (int): + Optional. How many days data should be + retained for. + """ + class RetentionMode(proto.Enum): + r"""Describes retention policy. + + Values: + RETENTION_MODE_UNSPECIFIED (0): + Default mode doesn't change environment + parameters. + RETENTION_MODE_ENABLED (1): + Retention policy is enabled. + RETENTION_MODE_DISABLED (2): + Retention policy is disabled. + """ + RETENTION_MODE_UNSPECIFIED = 0 + RETENTION_MODE_ENABLED = 1 + RETENTION_MODE_DISABLED = 2 + + retention_mode: RetentionMode = proto.Field( + proto.ENUM, + number=1, + enum=RetentionMode, + ) + retention_days: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/image_versions.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/image_versions.py new file mode 100644 index 000000000000..c5a7567cdb33 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/image_versions.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.orchestration.airflow.service.v1', + manifest={ + 'ListImageVersionsRequest', + 'ListImageVersionsResponse', + 'ImageVersion', + }, +) + + +class ListImageVersionsRequest(proto.Message): + r"""List ImageVersions in a project and location. + + Attributes: + parent (str): + List ImageVersions in the given project and + location, in the form: + "projects/{projectId}/locations/{locationId}". + page_size (int): + The maximum number of image_versions to return. + page_token (str): + The next_page_token value returned from a previous List + request, if any. + include_past_releases (bool): + Whether or not image versions from old + releases should be included. + """ + + 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, + ) + include_past_releases: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListImageVersionsResponse(proto.Message): + r"""The ImageVersions in a project and location. + + Attributes: + image_versions (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.ImageVersion]): + The list of supported ImageVersions in a + location. + next_page_token (str): + The page token used to query for the next + page if one exists. + """ + + @property + def raw_page(self): + return self + + image_versions: MutableSequence['ImageVersion'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ImageVersion', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ImageVersion(proto.Message): + r"""ImageVersion information + + Attributes: + image_version_id (str): + The string identifier of the ImageVersion, in + the form: "composer-x.y.z-airflow-a.b.c". + is_default (bool): + Whether this is the default ImageVersion used + by Composer during environment creation if no + input ImageVersion is specified. + supported_python_versions (MutableSequence[str]): + supported python versions + release_date (google.type.date_pb2.Date): + The date of the version release. + creation_disabled (bool): + Whether it is impossible to create an + environment with the image version. + upgrade_disabled (bool): + Whether it is impossible to upgrade an + environment running with the image version. + """ + + image_version_id: str = proto.Field( + proto.STRING, + number=1, + ) + is_default: bool = proto.Field( + proto.BOOL, + number=2, + ) + supported_python_versions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + release_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=4, + message=date_pb2.Date, + ) + creation_disabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + upgrade_disabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/operations.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/operations.py new file mode 100644 index 000000000000..cd908b4ed10c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/operations.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service.v1', + manifest={ + 'OperationMetadata', + }, +) + + +class OperationMetadata(proto.Message): + r"""Metadata describing an operation. + + Attributes: + state (google.cloud.orchestration.airflow.service_v1.types.OperationMetadata.State): + Output only. The current operation state. + operation_type (google.cloud.orchestration.airflow.service_v1.types.OperationMetadata.Type): + Output only. The type of operation being + performed. + resource (str): + Output only. The resource being operated on, as a `relative + resource + name `__. + resource_uuid (str): + Output only. The UUID of the resource being + operated on. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + submitted to the server. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the operation + terminated, regardless of its success. This + field is unset if the operation is still + ongoing. + """ + class State(proto.Enum): + r"""An enum describing the overall state of an operation. + + Values: + STATE_UNSPECIFIED (0): + Unused. + PENDING (1): + The operation has been created but is not yet + started. + RUNNING (2): + The operation is underway. + SUCCEEDED (3): + The operation completed successfully. + SUCCESSFUL (3): + No description available. + FAILED (4): + The operation is no longer running but did + not succeed. + """ + _pb_options = {'allow_alias': True} + STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + SUCCEEDED = 3 + SUCCESSFUL = 3 + FAILED = 4 + + class Type(proto.Enum): + r"""Type of longrunning operation. + + Values: + TYPE_UNSPECIFIED (0): + Unused. + CREATE (1): + A resource creation operation. + DELETE (2): + A resource deletion operation. + UPDATE (3): + A resource update operation. + CHECK (4): + A resource check operation. + SAVE_SNAPSHOT (5): + Saves snapshot of the resource operation. + LOAD_SNAPSHOT (6): + Loads snapshot of the resource operation. + DATABASE_FAILOVER (7): + Triggers failover of environment's Cloud SQL + instance (only for highly resilient + environments). + """ + TYPE_UNSPECIFIED = 0 + CREATE = 1 + DELETE = 2 + UPDATE = 3 + CHECK = 4 + SAVE_SNAPSHOT = 5 + LOAD_SNAPSHOT = 6 + DATABASE_FAILOVER = 7 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + operation_type: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + resource: str = proto.Field( + proto.STRING, + number=3, + ) + resource_uuid: str = proto.Field( + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/mypy.ini b/owl-bot-staging/google-cloud-orchestration-airflow/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/noxfile.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/noxfile.py new file mode 100644 index 000000000000..edbe3113b046 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow' + +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/orchestration/airflow/service_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/orchestration/airflow/service_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-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_async.py new file mode 100644 index 000000000000..6b0d1d7e863b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_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 CheckUpgrade +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_CheckUpgrade_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.orchestration.airflow import service_v1 + + +async def sample_check_upgrade(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.CheckUpgradeRequest( + environment="environment_value", + ) + + # Make the request + operation = client.check_upgrade(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_CheckUpgrade_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_sync.py new file mode 100644 index 000000000000..f8e30156ed47 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_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 CheckUpgrade +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_CheckUpgrade_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.orchestration.airflow import service_v1 + + +def sample_check_upgrade(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.CheckUpgradeRequest( + environment="environment_value", + ) + + # Make the request + operation = client.check_upgrade(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_CheckUpgrade_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py new file mode 100644 index 000000000000..9b5084ab9e58 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_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 CreateEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_CreateEnvironment_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.orchestration.airflow import service_v1 + + +async def sample_create_environment(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.CreateEnvironmentRequest( + ) + + # Make the request + operation = client.create_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_CreateEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py new file mode 100644 index 000000000000..b158ae726fdc --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_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 CreateEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_CreateEnvironment_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.orchestration.airflow import service_v1 + + +def sample_create_environment(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.CreateEnvironmentRequest( + ) + + # Make the request + operation = client.create_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_CreateEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_async.py new file mode 100644 index 000000000000..5ff6619dd120 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_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 CreateUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 + + +async def sample_create_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.CreateUserWorkloadsConfigMapRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_sync.py new file mode 100644 index 000000000000..6555bb873a67 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_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 CreateUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 + + +def sample_create_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.CreateUserWorkloadsConfigMapRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_async.py new file mode 100644 index 000000000000..224e00ca8610 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_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 CreateUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_CreateUserWorkloadsSecret_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.orchestration.airflow import service_v1 + + +async def sample_create_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.CreateUserWorkloadsSecretRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_CreateUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_sync.py new file mode 100644 index 000000000000..5005b96f04d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_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 CreateUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_CreateUserWorkloadsSecret_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.orchestration.airflow import service_v1 + + +def sample_create_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.CreateUserWorkloadsSecretRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_CreateUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py new file mode 100644 index 000000000000..e7fdea54a032 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_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 DatabaseFailover +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_DatabaseFailover_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.orchestration.airflow import service_v1 + + +async def sample_database_failover(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.DatabaseFailoverRequest( + ) + + # Make the request + operation = client.database_failover(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_DatabaseFailover_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py new file mode 100644 index 000000000000..6ca611bf168e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_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 DatabaseFailover +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_DatabaseFailover_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.orchestration.airflow import service_v1 + + +def sample_database_failover(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.DatabaseFailoverRequest( + ) + + # Make the request + operation = client.database_failover(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_DatabaseFailover_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py new file mode 100644 index 000000000000..101b8e274104 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_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 DeleteEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_DeleteEnvironment_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.orchestration.airflow import service_v1 + + +async def sample_delete_environment(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.DeleteEnvironmentRequest( + ) + + # Make the request + operation = client.delete_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_DeleteEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py new file mode 100644 index 000000000000..f9b835930e03 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_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 DeleteEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_DeleteEnvironment_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.orchestration.airflow import service_v1 + + +def sample_delete_environment(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.DeleteEnvironmentRequest( + ) + + # Make the request + operation = client.delete_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_DeleteEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_async.py new file mode 100644 index 000000000000..82f45b706fba --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 + + +async def sample_delete_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.DeleteUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_workloads_config_map(request=request) + + +# [END composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_sync.py new file mode 100644 index 000000000000..daac15ef4ff3 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 + + +def sample_delete_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.DeleteUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + client.delete_user_workloads_config_map(request=request) + + +# [END composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_async.py new file mode 100644 index 000000000000..beb6e11148e5 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_DeleteUserWorkloadsSecret_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.orchestration.airflow import service_v1 + + +async def sample_delete_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.DeleteUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_workloads_secret(request=request) + + +# [END composer_v1_generated_Environments_DeleteUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_sync.py new file mode 100644 index 000000000000..34ee80effba2 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_DeleteUserWorkloadsSecret_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.orchestration.airflow import service_v1 + + +def sample_delete_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.DeleteUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + client.delete_user_workloads_secret(request=request) + + +# [END composer_v1_generated_Environments_DeleteUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py new file mode 100644 index 000000000000..6eca2e668f9a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_ExecuteAirflowCommand_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.orchestration.airflow import service_v1 + + +async def sample_execute_airflow_command(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ExecuteAirflowCommandRequest( + ) + + # Make the request + response = await client.execute_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_ExecuteAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py new file mode 100644 index 000000000000..723d39ddffdf --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_ExecuteAirflowCommand_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.orchestration.airflow import service_v1 + + +def sample_execute_airflow_command(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.ExecuteAirflowCommandRequest( + ) + + # Make the request + response = client.execute_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_ExecuteAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py new file mode 100644 index 000000000000..dcafb0a9023d --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_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 FetchDatabaseProperties +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_FetchDatabaseProperties_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.orchestration.airflow import service_v1 + + +async def sample_fetch_database_properties(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.FetchDatabasePropertiesRequest( + environment="environment_value", + ) + + # Make the request + response = await client.fetch_database_properties(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_FetchDatabaseProperties_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py new file mode 100644 index 000000000000..311816055325 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_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 FetchDatabaseProperties +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_FetchDatabaseProperties_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.orchestration.airflow import service_v1 + + +def sample_fetch_database_properties(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.FetchDatabasePropertiesRequest( + environment="environment_value", + ) + + # Make the request + response = client.fetch_database_properties(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_FetchDatabaseProperties_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py new file mode 100644 index 000000000000..2c5ea9803969 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_GetEnvironment_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.orchestration.airflow import service_v1 + + +async def sample_get_environment(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.GetEnvironmentRequest( + ) + + # Make the request + response = await client.get_environment(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_GetEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py new file mode 100644 index 000000000000..f1655bd86f35 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_GetEnvironment_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.orchestration.airflow import service_v1 + + +def sample_get_environment(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.GetEnvironmentRequest( + ) + + # Make the request + response = client.get_environment(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_GetEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_async.py new file mode 100644 index 000000000000..aedfd3649839 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_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 GetUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_GetUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 + + +async def sample_get_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.GetUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_GetUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_sync.py new file mode 100644 index 000000000000..c7c245d66794 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_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 GetUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_GetUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 + + +def sample_get_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.GetUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_GetUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_async.py new file mode 100644 index 000000000000..71ad443f6408 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_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 GetUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_GetUserWorkloadsSecret_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.orchestration.airflow import service_v1 + + +async def sample_get_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.GetUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_GetUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_sync.py new file mode 100644 index 000000000000..3b22c2bc7c18 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_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 GetUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_GetUserWorkloadsSecret_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.orchestration.airflow import service_v1 + + +def sample_get_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.GetUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_GetUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py new file mode 100644 index 000000000000..3c01b1b9694f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_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 ListEnvironments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_ListEnvironments_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.orchestration.airflow import service_v1 + + +async def sample_list_environments(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ListEnvironmentsRequest( + ) + + # Make the request + page_result = client.list_environments(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END composer_v1_generated_Environments_ListEnvironments_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py new file mode 100644 index 000000000000..b801f09b44d4 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_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 ListEnvironments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_ListEnvironments_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.orchestration.airflow import service_v1 + + +def sample_list_environments(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.ListEnvironmentsRequest( + ) + + # Make the request + page_result = client.list_environments(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END composer_v1_generated_Environments_ListEnvironments_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_async.py new file mode 100644 index 000000000000..7d95cf57d729 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_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 ListUserWorkloadsConfigMaps +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_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.orchestration.airflow import service_v1 + + +async def sample_list_user_workloads_config_maps(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ListUserWorkloadsConfigMapsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_config_maps(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_sync.py new file mode 100644 index 000000000000..de0179278426 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_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 ListUserWorkloadsConfigMaps +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_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.orchestration.airflow import service_v1 + + +def sample_list_user_workloads_config_maps(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.ListUserWorkloadsConfigMapsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_config_maps(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_async.py new file mode 100644 index 000000000000..4634b9457358 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_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 ListUserWorkloadsSecrets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_ListUserWorkloadsSecrets_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.orchestration.airflow import service_v1 + + +async def sample_list_user_workloads_secrets(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ListUserWorkloadsSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_secrets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END composer_v1_generated_Environments_ListUserWorkloadsSecrets_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_sync.py new file mode 100644 index 000000000000..72406bc3eb93 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_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 ListUserWorkloadsSecrets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_ListUserWorkloadsSecrets_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.orchestration.airflow import service_v1 + + +def sample_list_user_workloads_secrets(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.ListUserWorkloadsSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_secrets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END composer_v1_generated_Environments_ListUserWorkloadsSecrets_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_async.py new file mode 100644 index 000000000000..a8fe64b38179 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_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 ListWorkloads +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_ListWorkloads_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.orchestration.airflow import service_v1 + + +async def sample_list_workloads(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END composer_v1_generated_Environments_ListWorkloads_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_sync.py new file mode 100644 index 000000000000..7131f654cf05 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_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 ListWorkloads +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_ListWorkloads_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.orchestration.airflow import service_v1 + + +def sample_list_workloads(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END composer_v1_generated_Environments_ListWorkloads_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py new file mode 100644 index 000000000000..853a8d1fba0c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_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 LoadSnapshot +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_LoadSnapshot_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.orchestration.airflow import service_v1 + + +async def sample_load_snapshot(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.LoadSnapshotRequest( + ) + + # Make the request + operation = client.load_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_LoadSnapshot_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py new file mode 100644 index 000000000000..a7896be32d11 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_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 LoadSnapshot +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_LoadSnapshot_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.orchestration.airflow import service_v1 + + +def sample_load_snapshot(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.LoadSnapshotRequest( + ) + + # Make the request + operation = client.load_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_LoadSnapshot_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py new file mode 100644 index 000000000000..16becaef7d3f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PollAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_PollAirflowCommand_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.orchestration.airflow import service_v1 + + +async def sample_poll_airflow_command(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.PollAirflowCommandRequest( + ) + + # Make the request + response = await client.poll_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_PollAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py new file mode 100644 index 000000000000..818dd2893280 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PollAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_PollAirflowCommand_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.orchestration.airflow import service_v1 + + +def sample_poll_airflow_command(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.PollAirflowCommandRequest( + ) + + # Make the request + response = client.poll_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_PollAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py new file mode 100644 index 000000000000..cb732a47e996 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_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 SaveSnapshot +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_SaveSnapshot_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.orchestration.airflow import service_v1 + + +async def sample_save_snapshot(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.SaveSnapshotRequest( + ) + + # Make the request + operation = client.save_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_SaveSnapshot_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py new file mode 100644 index 000000000000..cf0091fdb149 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_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 SaveSnapshot +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_SaveSnapshot_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.orchestration.airflow import service_v1 + + +def sample_save_snapshot(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.SaveSnapshotRequest( + ) + + # Make the request + operation = client.save_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_SaveSnapshot_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py new file mode 100644 index 000000000000..8c5a0204f31f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StopAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_StopAirflowCommand_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.orchestration.airflow import service_v1 + + +async def sample_stop_airflow_command(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.StopAirflowCommandRequest( + ) + + # Make the request + response = await client.stop_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_StopAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py new file mode 100644 index 000000000000..8528a3fa9f91 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StopAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_StopAirflowCommand_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.orchestration.airflow import service_v1 + + +def sample_stop_airflow_command(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.StopAirflowCommandRequest( + ) + + # Make the request + response = client.stop_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_StopAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py new file mode 100644 index 000000000000..6ffaec1b46a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_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 UpdateEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_UpdateEnvironment_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.orchestration.airflow import service_v1 + + +async def sample_update_environment(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.UpdateEnvironmentRequest( + ) + + # Make the request + operation = client.update_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_UpdateEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py new file mode 100644 index 000000000000..5bde272c7c12 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_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 UpdateEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_UpdateEnvironment_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.orchestration.airflow import service_v1 + + +def sample_update_environment(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.UpdateEnvironmentRequest( + ) + + # Make the request + operation = client.update_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_UpdateEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_async.py new file mode 100644 index 000000000000..cb78e06beea8 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 + + +async def sample_update_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.UpdateUserWorkloadsConfigMapRequest( + ) + + # Make the request + response = await client.update_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_sync.py new file mode 100644 index 000000000000..77c192805865 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 + + +def sample_update_user_workloads_config_map(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.UpdateUserWorkloadsConfigMapRequest( + ) + + # Make the request + response = client.update_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_async.py new file mode 100644 index 000000000000..339020bb8b0d --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_UpdateUserWorkloadsSecret_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.orchestration.airflow import service_v1 + + +async def sample_update_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1.UpdateUserWorkloadsSecretRequest( + ) + + # Make the request + response = await client.update_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_UpdateUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_sync.py new file mode 100644 index 000000000000..307caed04c66 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_Environments_UpdateUserWorkloadsSecret_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.orchestration.airflow import service_v1 + + +def sample_update_user_workloads_secret(): + # Create a client + client = service_v1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1.UpdateUserWorkloadsSecretRequest( + ) + + # Make the request + response = client.update_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1_generated_Environments_UpdateUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_async.py new file mode 100644 index 000000000000..66e9c5c442b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_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 ListImageVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_ImageVersions_ListImageVersions_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.orchestration.airflow import service_v1 + + +async def sample_list_image_versions(): + # Create a client + client = service_v1.ImageVersionsAsyncClient() + + # Initialize request argument(s) + request = service_v1.ListImageVersionsRequest( + ) + + # Make the request + page_result = client.list_image_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END composer_v1_generated_ImageVersions_ListImageVersions_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_sync.py new file mode 100644 index 000000000000..0506674847be --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_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 ListImageVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow + + +# [START composer_v1_generated_ImageVersions_ListImageVersions_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.orchestration.airflow import service_v1 + + +def sample_list_image_versions(): + # Create a client + client = service_v1.ImageVersionsClient() + + # Initialize request argument(s) + request = service_v1.ListImageVersionsRequest( + ) + + # Make the request + page_result = client.list_image_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END composer_v1_generated_ImageVersions_ListImageVersions_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json new file mode 100644 index 000000000000..37f3c1f31434 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json @@ -0,0 +1,4004 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.orchestration.airflow.service.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-orchestration-airflow", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.check_upgrade", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CheckUpgrade", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "CheckUpgrade" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.CheckUpgradeRequest" + }, + { + "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": "check_upgrade" + }, + "description": "Sample for CheckUpgrade", + "file": "composer_v1_generated_environments_check_upgrade_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_CheckUpgrade_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": "composer_v1_generated_environments_check_upgrade_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.check_upgrade", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CheckUpgrade", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "CheckUpgrade" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.CheckUpgradeRequest" + }, + { + "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": "check_upgrade" + }, + "description": "Sample for CheckUpgrade", + "file": "composer_v1_generated_environments_check_upgrade_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_CheckUpgrade_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": "composer_v1_generated_environments_check_upgrade_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.create_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.CreateEnvironmentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "environment", + "type": "google.cloud.orchestration.airflow.service_v1.types.Environment" + }, + { + "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_environment" + }, + "description": "Sample for CreateEnvironment", + "file": "composer_v1_generated_environments_create_environment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_CreateEnvironment_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_create_environment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.create_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.CreateEnvironmentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "environment", + "type": "google.cloud.orchestration.airflow.service_v1.types.Environment" + }, + { + "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_environment" + }, + "description": "Sample for CreateEnvironment", + "file": "composer_v1_generated_environments_create_environment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_CreateEnvironment_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_create_environment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.create_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsConfigMapRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_workloads_config_map", + "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", + "shortName": "create_user_workloads_config_map" + }, + "description": "Sample for CreateUserWorkloadsConfigMap", + "file": "composer_v1_generated_environments_create_user_workloads_config_map_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_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": "composer_v1_generated_environments_create_user_workloads_config_map_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.create_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsConfigMapRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_workloads_config_map", + "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", + "shortName": "create_user_workloads_config_map" + }, + "description": "Sample for CreateUserWorkloadsConfigMap", + "file": "composer_v1_generated_environments_create_user_workloads_config_map_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_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": "composer_v1_generated_environments_create_user_workloads_config_map_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.create_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsSecretRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_workloads_secret", + "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret", + "shortName": "create_user_workloads_secret" + }, + "description": "Sample for CreateUserWorkloadsSecret", + "file": "composer_v1_generated_environments_create_user_workloads_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_CreateUserWorkloadsSecret_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": "composer_v1_generated_environments_create_user_workloads_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.create_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsSecretRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_workloads_secret", + "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret", + "shortName": "create_user_workloads_secret" + }, + "description": "Sample for CreateUserWorkloadsSecret", + "file": "composer_v1_generated_environments_create_user_workloads_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_CreateUserWorkloadsSecret_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": "composer_v1_generated_environments_create_user_workloads_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.database_failover", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DatabaseFailover", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "DatabaseFailover" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.DatabaseFailoverRequest" + }, + { + "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": "database_failover" + }, + "description": "Sample for DatabaseFailover", + "file": "composer_v1_generated_environments_database_failover_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_DatabaseFailover_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_database_failover_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.database_failover", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DatabaseFailover", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "DatabaseFailover" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.DatabaseFailoverRequest" + }, + { + "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": "database_failover" + }, + "description": "Sample for DatabaseFailover", + "file": "composer_v1_generated_environments_database_failover_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_DatabaseFailover_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_database_failover_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.delete_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteEnvironmentRequest" + }, + { + "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_environment" + }, + "description": "Sample for DeleteEnvironment", + "file": "composer_v1_generated_environments_delete_environment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_DeleteEnvironment_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_delete_environment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.delete_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteEnvironmentRequest" + }, + { + "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_environment" + }, + "description": "Sample for DeleteEnvironment", + "file": "composer_v1_generated_environments_delete_environment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_DeleteEnvironment_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_delete_environment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.delete_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsConfigMapRequest" + }, + { + "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]]]" + } + ], + "shortName": "delete_user_workloads_config_map" + }, + "description": "Sample for DeleteUserWorkloadsConfigMap", + "file": "composer_v1_generated_environments_delete_user_workloads_config_map_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_delete_user_workloads_config_map_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.delete_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsConfigMapRequest" + }, + { + "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]]]" + } + ], + "shortName": "delete_user_workloads_config_map" + }, + "description": "Sample for DeleteUserWorkloadsConfigMap", + "file": "composer_v1_generated_environments_delete_user_workloads_config_map_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_delete_user_workloads_config_map_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.delete_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsSecretRequest" + }, + { + "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]]]" + } + ], + "shortName": "delete_user_workloads_secret" + }, + "description": "Sample for DeleteUserWorkloadsSecret", + "file": "composer_v1_generated_environments_delete_user_workloads_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_DeleteUserWorkloadsSecret_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_delete_user_workloads_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.delete_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsSecretRequest" + }, + { + "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]]]" + } + ], + "shortName": "delete_user_workloads_secret" + }, + "description": "Sample for DeleteUserWorkloadsSecret", + "file": "composer_v1_generated_environments_delete_user_workloads_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_DeleteUserWorkloadsSecret_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_delete_user_workloads_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.execute_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ExecuteAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "ExecuteAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandResponse", + "shortName": "execute_airflow_command" + }, + "description": "Sample for ExecuteAirflowCommand", + "file": "composer_v1_generated_environments_execute_airflow_command_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_ExecuteAirflowCommand_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_execute_airflow_command_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.execute_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ExecuteAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "ExecuteAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandResponse", + "shortName": "execute_airflow_command" + }, + "description": "Sample for ExecuteAirflowCommand", + "file": "composer_v1_generated_environments_execute_airflow_command_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_ExecuteAirflowCommand_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_execute_airflow_command_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.fetch_database_properties", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.FetchDatabaseProperties", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "FetchDatabaseProperties" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesResponse", + "shortName": "fetch_database_properties" + }, + "description": "Sample for FetchDatabaseProperties", + "file": "composer_v1_generated_environments_fetch_database_properties_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_FetchDatabaseProperties_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": "composer_v1_generated_environments_fetch_database_properties_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.fetch_database_properties", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.FetchDatabaseProperties", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "FetchDatabaseProperties" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesResponse", + "shortName": "fetch_database_properties" + }, + "description": "Sample for FetchDatabaseProperties", + "file": "composer_v1_generated_environments_fetch_database_properties_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_FetchDatabaseProperties_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": "composer_v1_generated_environments_fetch_database_properties_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.get_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "GetEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.GetEnvironmentRequest" + }, + { + "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.orchestration.airflow.service_v1.types.Environment", + "shortName": "get_environment" + }, + "description": "Sample for GetEnvironment", + "file": "composer_v1_generated_environments_get_environment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_GetEnvironment_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_get_environment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.get_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "GetEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.GetEnvironmentRequest" + }, + { + "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.orchestration.airflow.service_v1.types.Environment", + "shortName": "get_environment" + }, + "description": "Sample for GetEnvironment", + "file": "composer_v1_generated_environments_get_environment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_GetEnvironment_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_get_environment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.get_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "GetUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsConfigMapRequest" + }, + { + "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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", + "shortName": "get_user_workloads_config_map" + }, + "description": "Sample for GetUserWorkloadsConfigMap", + "file": "composer_v1_generated_environments_get_user_workloads_config_map_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_GetUserWorkloadsConfigMap_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": "composer_v1_generated_environments_get_user_workloads_config_map_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.get_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "GetUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsConfigMapRequest" + }, + { + "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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", + "shortName": "get_user_workloads_config_map" + }, + "description": "Sample for GetUserWorkloadsConfigMap", + "file": "composer_v1_generated_environments_get_user_workloads_config_map_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_GetUserWorkloadsConfigMap_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": "composer_v1_generated_environments_get_user_workloads_config_map_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.get_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "GetUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsSecretRequest" + }, + { + "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.orchestration.airflow.service_v1.types.UserWorkloadsSecret", + "shortName": "get_user_workloads_secret" + }, + "description": "Sample for GetUserWorkloadsSecret", + "file": "composer_v1_generated_environments_get_user_workloads_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_GetUserWorkloadsSecret_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": "composer_v1_generated_environments_get_user_workloads_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.get_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "GetUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsSecretRequest" + }, + { + "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.orchestration.airflow.service_v1.types.UserWorkloadsSecret", + "shortName": "get_user_workloads_secret" + }, + "description": "Sample for GetUserWorkloadsSecret", + "file": "composer_v1_generated_environments_get_user_workloads_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_GetUserWorkloadsSecret_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": "composer_v1_generated_environments_get_user_workloads_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.list_environments", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListEnvironments", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "ListEnvironments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest" + }, + { + "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.orchestration.airflow.service_v1.services.environments.pagers.ListEnvironmentsAsyncPager", + "shortName": "list_environments" + }, + "description": "Sample for ListEnvironments", + "file": "composer_v1_generated_environments_list_environments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_ListEnvironments_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_list_environments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.list_environments", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListEnvironments", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "ListEnvironments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest" + }, + { + "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.orchestration.airflow.service_v1.services.environments.pagers.ListEnvironmentsPager", + "shortName": "list_environments" + }, + "description": "Sample for ListEnvironments", + "file": "composer_v1_generated_environments_list_environments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_ListEnvironments_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_list_environments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.list_user_workloads_config_maps", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListUserWorkloadsConfigMaps", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "ListUserWorkloadsConfigMaps" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest" + }, + { + "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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsConfigMapsAsyncPager", + "shortName": "list_user_workloads_config_maps" + }, + "description": "Sample for ListUserWorkloadsConfigMaps", + "file": "composer_v1_generated_environments_list_user_workloads_config_maps_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_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": "composer_v1_generated_environments_list_user_workloads_config_maps_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.list_user_workloads_config_maps", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListUserWorkloadsConfigMaps", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "ListUserWorkloadsConfigMaps" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest" + }, + { + "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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsConfigMapsPager", + "shortName": "list_user_workloads_config_maps" + }, + "description": "Sample for ListUserWorkloadsConfigMaps", + "file": "composer_v1_generated_environments_list_user_workloads_config_maps_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_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": "composer_v1_generated_environments_list_user_workloads_config_maps_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.list_user_workloads_secrets", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListUserWorkloadsSecrets", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "ListUserWorkloadsSecrets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest" + }, + { + "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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsSecretsAsyncPager", + "shortName": "list_user_workloads_secrets" + }, + "description": "Sample for ListUserWorkloadsSecrets", + "file": "composer_v1_generated_environments_list_user_workloads_secrets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_ListUserWorkloadsSecrets_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": "composer_v1_generated_environments_list_user_workloads_secrets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.list_user_workloads_secrets", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListUserWorkloadsSecrets", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "ListUserWorkloadsSecrets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest" + }, + { + "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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsSecretsPager", + "shortName": "list_user_workloads_secrets" + }, + "description": "Sample for ListUserWorkloadsSecrets", + "file": "composer_v1_generated_environments_list_user_workloads_secrets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_ListUserWorkloadsSecrets_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": "composer_v1_generated_environments_list_user_workloads_secrets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.list_workloads", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListWorkloads", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "ListWorkloads" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest" + }, + { + "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.orchestration.airflow.service_v1.services.environments.pagers.ListWorkloadsAsyncPager", + "shortName": "list_workloads" + }, + "description": "Sample for ListWorkloads", + "file": "composer_v1_generated_environments_list_workloads_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_ListWorkloads_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": "composer_v1_generated_environments_list_workloads_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.list_workloads", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListWorkloads", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "ListWorkloads" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest" + }, + { + "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.orchestration.airflow.service_v1.services.environments.pagers.ListWorkloadsPager", + "shortName": "list_workloads" + }, + "description": "Sample for ListWorkloads", + "file": "composer_v1_generated_environments_list_workloads_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_ListWorkloads_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": "composer_v1_generated_environments_list_workloads_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.load_snapshot", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.LoadSnapshot", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "LoadSnapshot" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.LoadSnapshotRequest" + }, + { + "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": "load_snapshot" + }, + "description": "Sample for LoadSnapshot", + "file": "composer_v1_generated_environments_load_snapshot_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_LoadSnapshot_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_load_snapshot_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.load_snapshot", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.LoadSnapshot", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "LoadSnapshot" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.LoadSnapshotRequest" + }, + { + "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": "load_snapshot" + }, + "description": "Sample for LoadSnapshot", + "file": "composer_v1_generated_environments_load_snapshot_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_LoadSnapshot_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_load_snapshot_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.poll_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.PollAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "PollAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandResponse", + "shortName": "poll_airflow_command" + }, + "description": "Sample for PollAirflowCommand", + "file": "composer_v1_generated_environments_poll_airflow_command_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_PollAirflowCommand_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_poll_airflow_command_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.poll_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.PollAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "PollAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandResponse", + "shortName": "poll_airflow_command" + }, + "description": "Sample for PollAirflowCommand", + "file": "composer_v1_generated_environments_poll_airflow_command_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_PollAirflowCommand_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_poll_airflow_command_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.save_snapshot", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.SaveSnapshot", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "SaveSnapshot" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.SaveSnapshotRequest" + }, + { + "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": "save_snapshot" + }, + "description": "Sample for SaveSnapshot", + "file": "composer_v1_generated_environments_save_snapshot_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_SaveSnapshot_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_save_snapshot_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.save_snapshot", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.SaveSnapshot", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "SaveSnapshot" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.SaveSnapshotRequest" + }, + { + "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": "save_snapshot" + }, + "description": "Sample for SaveSnapshot", + "file": "composer_v1_generated_environments_save_snapshot_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_SaveSnapshot_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_save_snapshot_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.stop_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.StopAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "StopAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandResponse", + "shortName": "stop_airflow_command" + }, + "description": "Sample for StopAirflowCommand", + "file": "composer_v1_generated_environments_stop_airflow_command_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_StopAirflowCommand_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_stop_airflow_command_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.stop_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.StopAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "StopAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandResponse", + "shortName": "stop_airflow_command" + }, + "description": "Sample for StopAirflowCommand", + "file": "composer_v1_generated_environments_stop_airflow_command_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_StopAirflowCommand_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_stop_airflow_command_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.update_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateEnvironmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "environment", + "type": "google.cloud.orchestration.airflow.service_v1.types.Environment" + }, + { + "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_environment" + }, + "description": "Sample for UpdateEnvironment", + "file": "composer_v1_generated_environments_update_environment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_UpdateEnvironment_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_update_environment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.update_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateEnvironmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "environment", + "type": "google.cloud.orchestration.airflow.service_v1.types.Environment" + }, + { + "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_environment" + }, + "description": "Sample for UpdateEnvironment", + "file": "composer_v1_generated_environments_update_environment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_UpdateEnvironment_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_update_environment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.update_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsConfigMapRequest" + }, + { + "name": "user_workloads_config_map", + "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", + "shortName": "update_user_workloads_config_map" + }, + "description": "Sample for UpdateUserWorkloadsConfigMap", + "file": "composer_v1_generated_environments_update_user_workloads_config_map_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_update_user_workloads_config_map_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.update_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsConfigMapRequest" + }, + { + "name": "user_workloads_config_map", + "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", + "shortName": "update_user_workloads_config_map" + }, + "description": "Sample for UpdateUserWorkloadsConfigMap", + "file": "composer_v1_generated_environments_update_user_workloads_config_map_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_update_user_workloads_config_map_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.update_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsSecretRequest" + }, + { + "name": "user_workloads_secret", + "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret", + "shortName": "update_user_workloads_secret" + }, + "description": "Sample for UpdateUserWorkloadsSecret", + "file": "composer_v1_generated_environments_update_user_workloads_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_UpdateUserWorkloadsSecret_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_update_user_workloads_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.update_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsSecretRequest" + }, + { + "name": "user_workloads_secret", + "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret", + "shortName": "update_user_workloads_secret" + }, + "description": "Sample for UpdateUserWorkloadsSecret", + "file": "composer_v1_generated_environments_update_user_workloads_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_Environments_UpdateUserWorkloadsSecret_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_environments_update_user_workloads_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.ImageVersionsAsyncClient", + "shortName": "ImageVersionsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.ImageVersionsAsyncClient.list_image_versions", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.ImageVersions.ListImageVersions", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "shortName": "ImageVersions" + }, + "shortName": "ListImageVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest" + }, + { + "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.orchestration.airflow.service_v1.services.image_versions.pagers.ListImageVersionsAsyncPager", + "shortName": "list_image_versions" + }, + "description": "Sample for ListImageVersions", + "file": "composer_v1_generated_image_versions_list_image_versions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_ImageVersions_ListImageVersions_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_image_versions_list_image_versions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1.ImageVersionsClient", + "shortName": "ImageVersionsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1.ImageVersionsClient.list_image_versions", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1.ImageVersions.ListImageVersions", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", + "shortName": "ImageVersions" + }, + "shortName": "ListImageVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest" + }, + { + "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.orchestration.airflow.service_v1.services.image_versions.pagers.ListImageVersionsPager", + "shortName": "list_image_versions" + }, + "description": "Sample for ListImageVersions", + "file": "composer_v1_generated_image_versions_list_image_versions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1_generated_ImageVersions_ListImageVersions_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1_generated_image_versions_list_image_versions_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py new file mode 100644 index 000000000000..1d453d96293f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py @@ -0,0 +1,200 @@ +#! /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 serviceCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'check_upgrade': ('environment', 'image_version', ), + 'create_environment': ('parent', 'environment', ), + 'create_user_workloads_config_map': ('parent', 'user_workloads_config_map', ), + 'create_user_workloads_secret': ('parent', 'user_workloads_secret', ), + 'database_failover': ('environment', ), + 'delete_environment': ('name', ), + 'delete_user_workloads_config_map': ('name', ), + 'delete_user_workloads_secret': ('name', ), + 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), + 'fetch_database_properties': ('environment', ), + 'get_environment': ('name', ), + 'get_user_workloads_config_map': ('name', ), + 'get_user_workloads_secret': ('name', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), + 'list_user_workloads_config_maps': ('parent', 'page_size', 'page_token', ), + 'list_user_workloads_secrets': ('parent', 'page_size', 'page_token', ), + 'list_workloads': ('parent', 'page_size', 'page_token', 'filter', ), + 'load_snapshot': ('environment', 'snapshot_path', 'skip_pypi_packages_installation', 'skip_environment_variables_setting', 'skip_airflow_overrides_setting', 'skip_gcs_data_copying', ), + 'poll_airflow_command': ('environment', 'execution_id', 'pod', 'pod_namespace', 'next_line_number', ), + 'save_snapshot': ('environment', 'snapshot_location', ), + 'stop_airflow_command': ('environment', 'execution_id', 'pod', 'pod_namespace', 'force', ), + 'update_environment': ('name', 'environment', 'update_mask', ), + 'update_user_workloads_config_map': ('user_workloads_config_map', ), + 'update_user_workloads_secret': ('user_workloads_secret', ), + } + + 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=serviceCallTransformer(), +): + """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 service 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-orchestration-airflow/v1/setup.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/setup.py new file mode 100644 index 000000000000..49491dce0096 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow' + + +description = "Google Cloud Orchestration Airflow API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/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.0,!=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.0,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0", + "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", + "protobuf>=3.20.2,<7.0.0,!=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-orchestration-airflow" + +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-orchestration-airflow/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a77f12bc13e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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.0", +# 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-orchestration-airflow/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/tests/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/tests/unit/gapic/service_v1/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_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-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py new file mode 100644 index 000000000000..06d721386bd7 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py @@ -0,0 +1,17371 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1.services.environments import EnvironmentsAsyncClient +from google.cloud.orchestration.airflow.service_v1.services.environments import EnvironmentsClient +from google.cloud.orchestration.airflow.service_v1.services.environments import pagers +from google.cloud.orchestration.airflow.service_v1.services.environments import transports +from google.cloud.orchestration.airflow.service_v1.types import environments +from google.cloud.orchestration.airflow.service_v1.types import operations +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 + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +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 EnvironmentsClient._get_default_mtls_endpoint(None) is None + assert EnvironmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EnvironmentsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + EnvironmentsClient._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 EnvironmentsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert EnvironmentsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + EnvironmentsClient._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 EnvironmentsClient._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 EnvironmentsClient._get_client_cert_source(None, False) is None + assert EnvironmentsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert EnvironmentsClient._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 EnvironmentsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert EnvironmentsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = EnvironmentsClient._DEFAULT_UNIVERSE + default_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert EnvironmentsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert EnvironmentsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "always") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + assert EnvironmentsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + assert EnvironmentsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + EnvironmentsClient._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 EnvironmentsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert EnvironmentsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert EnvironmentsClient._get_universe_domain(None, None) == EnvironmentsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + EnvironmentsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = EnvironmentsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = EnvironmentsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (EnvironmentsClient, "grpc"), + (EnvironmentsAsyncClient, "grpc_asyncio"), + (EnvironmentsClient, "rest"), +]) +def test_environments_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 == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://composer.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EnvironmentsGrpcTransport, "grpc"), + (transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EnvironmentsRestTransport, "rest"), +]) +def test_environments_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", [ + (EnvironmentsClient, "grpc"), + (EnvironmentsAsyncClient, "grpc_asyncio"), + (EnvironmentsClient, "rest"), +]) +def test_environments_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 == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://composer.googleapis.com' + ) + + +def test_environments_client_get_transport_class(): + transport = EnvironmentsClient.get_transport_class() + available_transports = [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsRestTransport, + ] + assert transport in available_transports + + transport = EnvironmentsClient.get_transport_class("grpc") + assert transport == transports.EnvironmentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), +]) +@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) +def test_environments_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(EnvironmentsClient, '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(EnvironmentsClient, '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", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "true"), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "false"), +]) +@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_environments_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", [ + EnvironmentsClient, EnvironmentsAsyncClient +]) +@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) +def test_environments_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", [ + EnvironmentsClient, EnvironmentsAsyncClient +]) +@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) +def test_environments_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = EnvironmentsClient._DEFAULT_UNIVERSE + default_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EnvironmentsClient._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", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), +]) +def test_environments_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", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", None), +]) +def test_environments_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_environments_client_client_options_from_dict(): + with mock.patch('google.cloud.orchestration.airflow.service_v1.services.environments.transports.EnvironmentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EnvironmentsClient( + 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", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_environments_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( + "composer.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="composer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateEnvironmentRequest, + dict, +]) +def test_create_environment(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.CreateEnvironmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_environment_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 = EnvironmentsClient( + 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 = environments.CreateEnvironmentRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_environment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateEnvironmentRequest( + parent='parent_value', + ) + +def test_create_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + request = {} + client.create_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( + 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_environment 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_environment] = mock_rpc + + request = {} + await client.create_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.CreateEnvironmentRequest): + client = EnvironmentsAsyncClient( + 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_environment), + '__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_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.CreateEnvironmentRequest() + 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_environment_async_from_dict(): + await test_create_environment_async(request_type=dict) + +def test_create_environment_field_headers(): + client = EnvironmentsClient( + 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 = environments.CreateEnvironmentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_environment(request) + + # Establish that the 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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.CreateEnvironmentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_environment(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_environment_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__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_environment( + parent='parent_value', + environment=environments.Environment(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].environment + mock_val = environments.Environment(name='name_value') + assert arg == mock_val + + +def test_create_environment_flattened_error(): + client = EnvironmentsClient( + 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_environment( + environments.CreateEnvironmentRequest(), + parent='parent_value', + environment=environments.Environment(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_environment_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__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_environment( + parent='parent_value', + environment=environments.Environment(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].environment + mock_val = environments.Environment(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_environment_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_environment( + environments.CreateEnvironmentRequest(), + parent='parent_value', + environment=environments.Environment(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetEnvironmentRequest, + dict, +]) +def test_get_environment(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.Environment( + name='name_value', + uuid='uuid_value', + state=environments.Environment.State.CREATING, + satisfies_pzs=True, + satisfies_pzi=True, + ) + response = client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.GetEnvironmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.Environment) + assert response.name == 'name_value' + assert response.uuid == 'uuid_value' + assert response.state == environments.Environment.State.CREATING + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +def test_get_environment_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 = EnvironmentsClient( + 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 = environments.GetEnvironmentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_environment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetEnvironmentRequest( + name='name_value', + ) + +def test_get_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + request = {} + client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_environment(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_environment_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 = EnvironmentsAsyncClient( + 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_environment 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_environment] = mock_rpc + + request = {} + await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.GetEnvironmentRequest): + client = EnvironmentsAsyncClient( + 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment( + name='name_value', + uuid='uuid_value', + state=environments.Environment.State.CREATING, + satisfies_pzs=True, + satisfies_pzi=True, + )) + response = await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.GetEnvironmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.Environment) + assert response.name == 'name_value' + assert response.uuid == 'uuid_value' + assert response.state == environments.Environment.State.CREATING + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.asyncio +async def test_get_environment_async_from_dict(): + await test_get_environment_async(request_type=dict) + +def test_get_environment_field_headers(): + client = EnvironmentsClient( + 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 = environments.GetEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value = environments.Environment() + client.get_environment(request) + + # Establish that the 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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.GetEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment()) + await client.get_environment(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_environment_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.Environment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_environment( + 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_environment_flattened_error(): + client = EnvironmentsClient( + 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_environment( + environments.GetEnvironmentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_environment_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.Environment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_environment( + 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_environment_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_environment( + environments.GetEnvironmentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListEnvironmentsRequest, + dict, +]) +def test_list_environments(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListEnvironmentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.ListEnvironmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnvironmentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_environments_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 = EnvironmentsClient( + 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 = environments.ListEnvironmentsRequest( + 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_environments), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_environments(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListEnvironmentsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_environments_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 = EnvironmentsClient( + 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_environments 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_environments] = mock_rpc + request = {} + client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_environments(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_environments_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 = EnvironmentsAsyncClient( + 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_environments 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_environments] = mock_rpc + + request = {} + await client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_environments(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_environments_async(transport: str = 'grpc_asyncio', request_type=environments.ListEnvironmentsRequest): + client = EnvironmentsAsyncClient( + 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_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.ListEnvironmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnvironmentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_environments_async_from_dict(): + await test_list_environments_async(request_type=dict) + +def test_list_environments_field_headers(): + client = EnvironmentsClient( + 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 = environments.ListEnvironmentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value = environments.ListEnvironmentsResponse() + client.list_environments(request) + + # Establish that the 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_environments_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.ListEnvironmentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse()) + await client.list_environments(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_environments_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListEnvironmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_environments( + 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_environments_flattened_error(): + client = EnvironmentsClient( + 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_environments( + environments.ListEnvironmentsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_environments_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListEnvironmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_environments( + 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_environments_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_environments( + environments.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +def test_list_environments_pager(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_environments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + environments.Environment(), + ], + next_page_token='abc', + ), + environments.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + ], + next_page_token='ghi', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_environments(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, environments.Environment) + for i in results) +def test_list_environments_pages(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_environments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + environments.Environment(), + ], + next_page_token='abc', + ), + environments.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + ], + next_page_token='ghi', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_environments(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_environments_async_pager(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + environments.Environment(), + ], + next_page_token='abc', + ), + environments.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + ], + next_page_token='ghi', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_environments(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, environments.Environment) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_environments_async_pages(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + environments.Environment(), + ], + next_page_token='abc', + ), + environments.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + ], + next_page_token='ghi', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + ], + ), + 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_environments(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", [ + environments.UpdateEnvironmentRequest, + dict, +]) +def test_update_environment(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.UpdateEnvironmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_environment_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 = EnvironmentsClient( + 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 = environments.UpdateEnvironmentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_environment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateEnvironmentRequest( + name='name_value', + ) + +def test_update_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + request = {} + client.update_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( + 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_environment 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_environment] = mock_rpc + + request = {} + await client.update_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateEnvironmentRequest): + client = EnvironmentsAsyncClient( + 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_environment), + '__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_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.UpdateEnvironmentRequest() + 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_environment_async_from_dict(): + await test_update_environment_async(request_type=dict) + +def test_update_environment_field_headers(): + client = EnvironmentsClient( + 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 = environments.UpdateEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.UpdateEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_update_environment_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__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_environment( + name='name_value', + environment=environments.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].environment + mock_val = environments.Environment(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_environment_flattened_error(): + client = EnvironmentsClient( + 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_environment( + environments.UpdateEnvironmentRequest(), + name='name_value', + environment=environments.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_environment_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__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_environment( + name='name_value', + environment=environments.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].environment + mock_val = environments.Environment(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_environment_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_environment( + environments.UpdateEnvironmentRequest(), + name='name_value', + environment=environments.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteEnvironmentRequest, + dict, +]) +def test_delete_environment(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.DeleteEnvironmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_environment_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 = EnvironmentsClient( + 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 = environments.DeleteEnvironmentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_environment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteEnvironmentRequest( + name='name_value', + ) + +def test_delete_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + request = {} + client.delete_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( + 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_environment 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_environment] = mock_rpc + + request = {} + await client.delete_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteEnvironmentRequest): + client = EnvironmentsAsyncClient( + 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_environment), + '__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_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.DeleteEnvironmentRequest() + 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_environment_async_from_dict(): + await test_delete_environment_async(request_type=dict) + +def test_delete_environment_field_headers(): + client = EnvironmentsClient( + 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 = environments.DeleteEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_environment(request) + + # Establish that the 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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.DeleteEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_environment(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_environment_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__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_environment( + 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_environment_flattened_error(): + client = EnvironmentsClient( + 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_environment( + environments.DeleteEnvironmentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_environment_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__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_environment( + 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_environment_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_environment( + environments.DeleteEnvironmentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ExecuteAirflowCommandRequest, + dict, +]) +def test_execute_airflow_command(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.execute_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ExecuteAirflowCommandResponse( + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + error='error_value', + ) + response = client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.ExecuteAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.ExecuteAirflowCommandResponse) + assert response.execution_id == 'execution_id_value' + assert response.pod == 'pod_value' + assert response.pod_namespace == 'pod_namespace_value' + assert response.error == 'error_value' + + +def test_execute_airflow_command_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 = EnvironmentsClient( + 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 = environments.ExecuteAirflowCommandRequest( + environment='environment_value', + command='command_value', + subcommand='subcommand_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.execute_airflow_command(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ExecuteAirflowCommandRequest( + environment='environment_value', + command='command_value', + subcommand='subcommand_value', + ) + +def test_execute_airflow_command_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 = EnvironmentsClient( + 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc + request = {} + client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.execute_airflow_command(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_execute_airflow_command_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 = EnvironmentsAsyncClient( + 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc + + request = {} + await client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.execute_airflow_command(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_execute_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.ExecuteAirflowCommandRequest): + client = EnvironmentsAsyncClient( + 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.execute_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse( + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + error='error_value', + )) + response = await client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.ExecuteAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.ExecuteAirflowCommandResponse) + assert response.execution_id == 'execution_id_value' + assert response.pod == 'pod_value' + assert response.pod_namespace == 'pod_namespace_value' + assert response.error == 'error_value' + + +@pytest.mark.asyncio +async def test_execute_airflow_command_async_from_dict(): + await test_execute_airflow_command_async(request_type=dict) + +def test_execute_airflow_command_field_headers(): + client = EnvironmentsClient( + 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 = environments.ExecuteAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + call.return_value = environments.ExecuteAirflowCommandResponse() + client.execute_airflow_command(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_execute_airflow_command_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.ExecuteAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse()) + await client.execute_airflow_command(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.StopAirflowCommandRequest, + dict, +]) +def test_stop_airflow_command(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.stop_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.StopAirflowCommandResponse( + is_done=True, + output=['output_value'], + ) + response = client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.StopAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ['output_value'] + + +def test_stop_airflow_command_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 = EnvironmentsClient( + 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 = environments.StopAirflowCommandRequest( + environment='environment_value', + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.stop_airflow_command(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.StopAirflowCommandRequest( + environment='environment_value', + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + ) + +def test_stop_airflow_command_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 = EnvironmentsClient( + 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc + request = {} + client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stop_airflow_command(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_stop_airflow_command_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 = EnvironmentsAsyncClient( + 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc + + request = {} + await client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.stop_airflow_command(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_stop_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.StopAirflowCommandRequest): + client = EnvironmentsAsyncClient( + 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.stop_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse( + is_done=True, + output=['output_value'], + )) + response = await client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.StopAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ['output_value'] + + +@pytest.mark.asyncio +async def test_stop_airflow_command_async_from_dict(): + await test_stop_airflow_command_async(request_type=dict) + +def test_stop_airflow_command_field_headers(): + client = EnvironmentsClient( + 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 = environments.StopAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + call.return_value = environments.StopAirflowCommandResponse() + client.stop_airflow_command(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_stop_airflow_command_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.StopAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse()) + await client.stop_airflow_command(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.PollAirflowCommandRequest, + dict, +]) +def test_poll_airflow_command(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.poll_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.PollAirflowCommandResponse( + output_end=True, + ) + response = client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.PollAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.PollAirflowCommandResponse) + assert response.output_end is True + + +def test_poll_airflow_command_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 = EnvironmentsClient( + 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 = environments.PollAirflowCommandRequest( + environment='environment_value', + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.poll_airflow_command(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.PollAirflowCommandRequest( + environment='environment_value', + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + ) + +def test_poll_airflow_command_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 = EnvironmentsClient( + 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc + request = {} + client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.poll_airflow_command(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_poll_airflow_command_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 = EnvironmentsAsyncClient( + 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc + + request = {} + await client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.poll_airflow_command(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_poll_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.PollAirflowCommandRequest): + client = EnvironmentsAsyncClient( + 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.poll_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse( + output_end=True, + )) + response = await client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.PollAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.PollAirflowCommandResponse) + assert response.output_end is True + + +@pytest.mark.asyncio +async def test_poll_airflow_command_async_from_dict(): + await test_poll_airflow_command_async(request_type=dict) + +def test_poll_airflow_command_field_headers(): + client = EnvironmentsClient( + 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 = environments.PollAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + call.return_value = environments.PollAirflowCommandResponse() + client.poll_airflow_command(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_poll_airflow_command_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.PollAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse()) + await client.poll_airflow_command(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.ListWorkloadsRequest, + dict, +]) +def test_list_workloads(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_workloads), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListWorkloadsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.ListWorkloadsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_workloads_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 = EnvironmentsClient( + 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 = environments.ListWorkloadsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workloads(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListWorkloadsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_workloads_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 = EnvironmentsClient( + 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_workloads 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_workloads] = mock_rpc + request = {} + client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workloads(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_workloads_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 = EnvironmentsAsyncClient( + 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_workloads 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_workloads] = mock_rpc + + request = {} + await client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_workloads(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_workloads_async(transport: str = 'grpc_asyncio', request_type=environments.ListWorkloadsRequest): + client = EnvironmentsAsyncClient( + 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_workloads), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.ListWorkloadsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_workloads_async_from_dict(): + await test_list_workloads_async(request_type=dict) + +def test_list_workloads_field_headers(): + client = EnvironmentsClient( + 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 = environments.ListWorkloadsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + call.return_value = environments.ListWorkloadsResponse() + client.list_workloads(request) + + # Establish that the 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_workloads_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.ListWorkloadsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse()) + await client.list_workloads(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_workloads_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListWorkloadsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workloads( + 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_workloads_flattened_error(): + client = EnvironmentsClient( + 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_workloads( + environments.ListWorkloadsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workloads_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListWorkloadsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workloads( + 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_workloads_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_workloads( + environments.ListWorkloadsRequest(), + parent='parent_value', + ) + + +def test_list_workloads_pager(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_workloads), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='abc', + ), + environments.ListWorkloadsResponse( + workloads=[], + next_page_token='def', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='ghi', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workloads(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, environments.ListWorkloadsResponse.ComposerWorkload) + for i in results) +def test_list_workloads_pages(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_workloads), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='abc', + ), + environments.ListWorkloadsResponse( + workloads=[], + next_page_token='def', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='ghi', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workloads(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_workloads_async_pager(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='abc', + ), + environments.ListWorkloadsResponse( + workloads=[], + next_page_token='def', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='ghi', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workloads(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, environments.ListWorkloadsResponse.ComposerWorkload) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workloads_async_pages(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='abc', + ), + environments.ListWorkloadsResponse( + workloads=[], + next_page_token='def', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='ghi', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + ), + 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_workloads(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", [ + environments.CheckUpgradeRequest, + dict, +]) +def test_check_upgrade(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.check_upgrade), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.check_upgrade(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.CheckUpgradeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_check_upgrade_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 = EnvironmentsClient( + 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 = environments.CheckUpgradeRequest( + environment='environment_value', + image_version='image_version_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.check_upgrade(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CheckUpgradeRequest( + environment='environment_value', + image_version='image_version_value', + ) + +def test_check_upgrade_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 = EnvironmentsClient( + 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.check_upgrade 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.check_upgrade] = mock_rpc + request = {} + client.check_upgrade(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.check_upgrade(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_check_upgrade_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 = EnvironmentsAsyncClient( + 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.check_upgrade 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.check_upgrade] = mock_rpc + + request = {} + await client.check_upgrade(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.check_upgrade(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_check_upgrade_async(transport: str = 'grpc_asyncio', request_type=environments.CheckUpgradeRequest): + client = EnvironmentsAsyncClient( + 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.check_upgrade), + '__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.check_upgrade(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.CheckUpgradeRequest() + 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_check_upgrade_async_from_dict(): + await test_check_upgrade_async(request_type=dict) + +def test_check_upgrade_field_headers(): + client = EnvironmentsClient( + 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 = environments.CheckUpgradeRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.check_upgrade(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_check_upgrade_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.CheckUpgradeRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.check_upgrade(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsSecretRequest, + dict, +]) +def test_create_user_workloads_secret(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret( + name='name_value', + ) + response = client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.CreateUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +def test_create_user_workloads_secret_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 = EnvironmentsClient( + 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 = environments.CreateUserWorkloadsSecretRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_user_workloads_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsSecretRequest( + parent='parent_value', + ) + +def test_create_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + request = {} + client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + await client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.CreateUserWorkloadsSecretRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + response = await client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.CreateUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_user_workloads_secret_async_from_dict(): + await test_create_user_workloads_secret_async(request_type=dict) + +def test_create_user_workloads_secret_field_headers(): + client = EnvironmentsClient( + 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 = environments.CreateUserWorkloadsSecretRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.create_user_workloads_secret(request) + + # Establish that the 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_user_workloads_secret_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.CreateUserWorkloadsSecretRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + await client.create_user_workloads_secret(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_user_workloads_secret_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user_workloads_secret( + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_workloads_secret + mock_val = environments.UserWorkloadsSecret(name='name_value') + assert arg == mock_val + + +def test_create_user_workloads_secret_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.CreateUserWorkloadsSecretRequest(), + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_user_workloads_secret_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user_workloads_secret( + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_workloads_secret + mock_val = environments.UserWorkloadsSecret(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_user_workloads_secret_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret( + environments.CreateUserWorkloadsSecretRequest(), + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsSecretRequest, + dict, +]) +def test_get_user_workloads_secret(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret( + name='name_value', + ) + response = client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.GetUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +def test_get_user_workloads_secret_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 = EnvironmentsClient( + 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 = environments.GetUserWorkloadsSecretRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_user_workloads_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsSecretRequest( + name='name_value', + ) + +def test_get_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + request = {} + client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + await client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.GetUserWorkloadsSecretRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + response = await client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.GetUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_user_workloads_secret_async_from_dict(): + await test_get_user_workloads_secret_async(request_type=dict) + +def test_get_user_workloads_secret_field_headers(): + client = EnvironmentsClient( + 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 = environments.GetUserWorkloadsSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.get_user_workloads_secret(request) + + # Establish that the 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_user_workloads_secret_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.GetUserWorkloadsSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + await client.get_user_workloads_secret(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_user_workloads_secret_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user_workloads_secret( + 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_user_workloads_secret_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.GetUserWorkloadsSecretRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_user_workloads_secret_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user_workloads_secret( + 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_user_workloads_secret_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret( + environments.GetUserWorkloadsSecretRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsSecretsRequest, + dict, +]) +def test_list_user_workloads_secrets(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsSecretsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.ListUserWorkloadsSecretsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsSecretsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_user_workloads_secrets_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 = EnvironmentsClient( + 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 = environments.ListUserWorkloadsSecretsRequest( + 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_user_workloads_secrets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_user_workloads_secrets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsSecretsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_user_workloads_secrets_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 = EnvironmentsClient( + 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc + request = {} + client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_user_workloads_secrets(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_user_workloads_secrets_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 = EnvironmentsAsyncClient( + 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc + + request = {} + await client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_user_workloads_secrets(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_user_workloads_secrets_async(transport: str = 'grpc_asyncio', request_type=environments.ListUserWorkloadsSecretsRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.ListUserWorkloadsSecretsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsSecretsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_user_workloads_secrets_async_from_dict(): + await test_list_user_workloads_secrets_async(request_type=dict) + +def test_list_user_workloads_secrets_field_headers(): + client = EnvironmentsClient( + 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 = environments.ListUserWorkloadsSecretsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + call.return_value = environments.ListUserWorkloadsSecretsResponse() + client.list_user_workloads_secrets(request) + + # Establish that the 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_user_workloads_secrets_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.ListUserWorkloadsSecretsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse()) + await client.list_user_workloads_secrets(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_user_workloads_secrets_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsSecretsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_user_workloads_secrets( + 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_user_workloads_secrets_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_secrets( + environments.ListUserWorkloadsSecretsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_user_workloads_secrets_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsSecretsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_user_workloads_secrets( + 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_user_workloads_secrets_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_secrets( + environments.ListUserWorkloadsSecretsRequest(), + parent='parent_value', + ) + + +def test_list_user_workloads_secrets_pager(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_user_workloads_secrets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[], + next_page_token='def', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_user_workloads_secrets(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, environments.UserWorkloadsSecret) + for i in results) +def test_list_user_workloads_secrets_pages(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_user_workloads_secrets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[], + next_page_token='def', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + ), + RuntimeError, + ) + pages = list(client.list_user_workloads_secrets(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_user_workloads_secrets_async_pager(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[], + next_page_token='def', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_user_workloads_secrets(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, environments.UserWorkloadsSecret) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_user_workloads_secrets_async_pages(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[], + next_page_token='def', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + ), + 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_user_workloads_secrets(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", [ + environments.UpdateUserWorkloadsSecretRequest, + dict, +]) +def test_update_user_workloads_secret(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret( + name='name_value', + ) + response = client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.UpdateUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +def test_update_user_workloads_secret_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 = EnvironmentsClient( + 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 = environments.UpdateUserWorkloadsSecretRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_user_workloads_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsSecretRequest( + ) + +def test_update_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + request = {} + client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + await client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateUserWorkloadsSecretRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + response = await client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.UpdateUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_user_workloads_secret_async_from_dict(): + await test_update_user_workloads_secret_async(request_type=dict) + +def test_update_user_workloads_secret_field_headers(): + client = EnvironmentsClient( + 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 = environments.UpdateUserWorkloadsSecretRequest() + + request.user_workloads_secret.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.update_user_workloads_secret(request) + + # Establish that the 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', + 'user_workloads_secret.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_user_workloads_secret_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.UpdateUserWorkloadsSecretRequest() + + request.user_workloads_secret.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + await client.update_user_workloads_secret(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', + 'user_workloads_secret.name=name_value', + ) in kw['metadata'] + + +def test_update_user_workloads_secret_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user_workloads_secret( + user_workloads_secret=environments.UserWorkloadsSecret(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].user_workloads_secret + mock_val = environments.UserWorkloadsSecret(name='name_value') + assert arg == mock_val + + +def test_update_user_workloads_secret_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.UpdateUserWorkloadsSecretRequest(), + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_user_workloads_secret_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user_workloads_secret( + user_workloads_secret=environments.UserWorkloadsSecret(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].user_workloads_secret + mock_val = environments.UserWorkloadsSecret(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_user_workloads_secret_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret( + environments.UpdateUserWorkloadsSecretRequest(), + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsSecretRequest, + dict, +]) +def test_delete_user_workloads_secret(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.DeleteUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_workloads_secret_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 = EnvironmentsClient( + 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 = environments.DeleteUserWorkloadsSecretRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_user_workloads_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsSecretRequest( + name='name_value', + ) + +def test_delete_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + request = {} + client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + await client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteUserWorkloadsSecretRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.DeleteUserWorkloadsSecretRequest() + 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_user_workloads_secret_async_from_dict(): + await test_delete_user_workloads_secret_async(request_type=dict) + +def test_delete_user_workloads_secret_field_headers(): + client = EnvironmentsClient( + 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 = environments.DeleteUserWorkloadsSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + call.return_value = None + client.delete_user_workloads_secret(request) + + # Establish that the 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_user_workloads_secret_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.DeleteUserWorkloadsSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_workloads_secret(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_user_workloads_secret_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user_workloads_secret( + 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_user_workloads_secret_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.DeleteUserWorkloadsSecretRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_user_workloads_secret_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user_workloads_secret( + 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_user_workloads_secret_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret( + environments.DeleteUserWorkloadsSecretRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsConfigMapRequest, + dict, +]) +def test_create_user_workloads_config_map(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap( + name='name_value', + ) + response = client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.CreateUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +def test_create_user_workloads_config_map_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 = EnvironmentsClient( + 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 = environments.CreateUserWorkloadsConfigMapRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_user_workloads_config_map(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsConfigMapRequest( + parent='parent_value', + ) + +def test_create_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + request = {} + client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + await client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.CreateUserWorkloadsConfigMapRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + response = await client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.CreateUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_user_workloads_config_map_async_from_dict(): + await test_create_user_workloads_config_map_async(request_type=dict) + +def test_create_user_workloads_config_map_field_headers(): + client = EnvironmentsClient( + 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 = environments.CreateUserWorkloadsConfigMapRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.create_user_workloads_config_map(request) + + # Establish that the 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_user_workloads_config_map_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.CreateUserWorkloadsConfigMapRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + await client.create_user_workloads_config_map(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_user_workloads_config_map_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user_workloads_config_map( + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_workloads_config_map + mock_val = environments.UserWorkloadsConfigMap(name='name_value') + assert arg == mock_val + + +def test_create_user_workloads_config_map_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.CreateUserWorkloadsConfigMapRequest(), + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_user_workloads_config_map_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user_workloads_config_map( + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_workloads_config_map + mock_val = environments.UserWorkloadsConfigMap(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_user_workloads_config_map_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map( + environments.CreateUserWorkloadsConfigMapRequest(), + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsConfigMapRequest, + dict, +]) +def test_get_user_workloads_config_map(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap( + name='name_value', + ) + response = client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.GetUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +def test_get_user_workloads_config_map_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 = EnvironmentsClient( + 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 = environments.GetUserWorkloadsConfigMapRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_user_workloads_config_map(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsConfigMapRequest( + name='name_value', + ) + +def test_get_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + request = {} + client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + await client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.GetUserWorkloadsConfigMapRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + response = await client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.GetUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_user_workloads_config_map_async_from_dict(): + await test_get_user_workloads_config_map_async(request_type=dict) + +def test_get_user_workloads_config_map_field_headers(): + client = EnvironmentsClient( + 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 = environments.GetUserWorkloadsConfigMapRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.get_user_workloads_config_map(request) + + # Establish that the 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_user_workloads_config_map_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.GetUserWorkloadsConfigMapRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + await client.get_user_workloads_config_map(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_user_workloads_config_map_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user_workloads_config_map( + 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_user_workloads_config_map_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.GetUserWorkloadsConfigMapRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_user_workloads_config_map_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user_workloads_config_map( + 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_user_workloads_config_map_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map( + environments.GetUserWorkloadsConfigMapRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsConfigMapsRequest, + dict, +]) +def test_list_user_workloads_config_maps(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_config_maps), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsConfigMapsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.ListUserWorkloadsConfigMapsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsConfigMapsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_user_workloads_config_maps_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 = EnvironmentsClient( + 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 = environments.ListUserWorkloadsConfigMapsRequest( + 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_user_workloads_config_maps), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_user_workloads_config_maps(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsConfigMapsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_user_workloads_config_maps_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 = EnvironmentsClient( + 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc + request = {} + client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_user_workloads_config_maps(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_user_workloads_config_maps_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 = EnvironmentsAsyncClient( + 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc + + request = {} + await client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_user_workloads_config_maps(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_user_workloads_config_maps_async(transport: str = 'grpc_asyncio', request_type=environments.ListUserWorkloadsConfigMapsRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_maps), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.ListUserWorkloadsConfigMapsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsConfigMapsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_user_workloads_config_maps_async_from_dict(): + await test_list_user_workloads_config_maps_async(request_type=dict) + +def test_list_user_workloads_config_maps_field_headers(): + client = EnvironmentsClient( + 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 = environments.ListUserWorkloadsConfigMapsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + call.return_value = environments.ListUserWorkloadsConfigMapsResponse() + client.list_user_workloads_config_maps(request) + + # Establish that the 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_user_workloads_config_maps_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.ListUserWorkloadsConfigMapsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse()) + await client.list_user_workloads_config_maps(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_user_workloads_config_maps_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsConfigMapsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_user_workloads_config_maps( + 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_user_workloads_config_maps_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_config_maps( + environments.ListUserWorkloadsConfigMapsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_user_workloads_config_maps_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsConfigMapsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_user_workloads_config_maps( + 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_user_workloads_config_maps_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_maps( + environments.ListUserWorkloadsConfigMapsRequest(), + parent='parent_value', + ) + + +def test_list_user_workloads_config_maps_pager(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_user_workloads_config_maps), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[], + next_page_token='def', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_user_workloads_config_maps(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, environments.UserWorkloadsConfigMap) + for i in results) +def test_list_user_workloads_config_maps_pages(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_user_workloads_config_maps), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[], + next_page_token='def', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + ), + RuntimeError, + ) + pages = list(client.list_user_workloads_config_maps(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_user_workloads_config_maps_async_pager(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[], + next_page_token='def', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_user_workloads_config_maps(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, environments.UserWorkloadsConfigMap) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_user_workloads_config_maps_async_pages(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[], + next_page_token='def', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + ), + 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_user_workloads_config_maps(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", [ + environments.UpdateUserWorkloadsConfigMapRequest, + dict, +]) +def test_update_user_workloads_config_map(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap( + name='name_value', + ) + response = client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.UpdateUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +def test_update_user_workloads_config_map_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 = EnvironmentsClient( + 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 = environments.UpdateUserWorkloadsConfigMapRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_user_workloads_config_map(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest( + ) + +def test_update_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + request = {} + client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + await client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateUserWorkloadsConfigMapRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + response = await client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.UpdateUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_user_workloads_config_map_async_from_dict(): + await test_update_user_workloads_config_map_async(request_type=dict) + +def test_update_user_workloads_config_map_field_headers(): + client = EnvironmentsClient( + 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 = environments.UpdateUserWorkloadsConfigMapRequest() + + request.user_workloads_config_map.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.update_user_workloads_config_map(request) + + # Establish that the 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', + 'user_workloads_config_map.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_user_workloads_config_map_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.UpdateUserWorkloadsConfigMapRequest() + + request.user_workloads_config_map.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + await client.update_user_workloads_config_map(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', + 'user_workloads_config_map.name=name_value', + ) in kw['metadata'] + + +def test_update_user_workloads_config_map_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user_workloads_config_map( + user_workloads_config_map=environments.UserWorkloadsConfigMap(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].user_workloads_config_map + mock_val = environments.UserWorkloadsConfigMap(name='name_value') + assert arg == mock_val + + +def test_update_user_workloads_config_map_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.UpdateUserWorkloadsConfigMapRequest(), + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_user_workloads_config_map_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user_workloads_config_map( + user_workloads_config_map=environments.UserWorkloadsConfigMap(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].user_workloads_config_map + mock_val = environments.UserWorkloadsConfigMap(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_user_workloads_config_map_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map( + environments.UpdateUserWorkloadsConfigMapRequest(), + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsConfigMapRequest, + dict, +]) +def test_delete_user_workloads_config_map(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.DeleteUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_workloads_config_map_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 = EnvironmentsClient( + 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 = environments.DeleteUserWorkloadsConfigMapRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_user_workloads_config_map(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest( + name='name_value', + ) + +def test_delete_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + request = {} + client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + await client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteUserWorkloadsConfigMapRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.DeleteUserWorkloadsConfigMapRequest() + 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_user_workloads_config_map_async_from_dict(): + await test_delete_user_workloads_config_map_async(request_type=dict) + +def test_delete_user_workloads_config_map_field_headers(): + client = EnvironmentsClient( + 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 = environments.DeleteUserWorkloadsConfigMapRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + call.return_value = None + client.delete_user_workloads_config_map(request) + + # Establish that the 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_user_workloads_config_map_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.DeleteUserWorkloadsConfigMapRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_workloads_config_map(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_user_workloads_config_map_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user_workloads_config_map( + 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_user_workloads_config_map_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.DeleteUserWorkloadsConfigMapRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_user_workloads_config_map_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user_workloads_config_map( + 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_user_workloads_config_map_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map( + environments.DeleteUserWorkloadsConfigMapRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.SaveSnapshotRequest, + dict, +]) +def test_save_snapshot(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.save_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.save_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.SaveSnapshotRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_save_snapshot_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 = EnvironmentsClient( + 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 = environments.SaveSnapshotRequest( + environment='environment_value', + snapshot_location='snapshot_location_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.save_snapshot(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.SaveSnapshotRequest( + environment='environment_value', + snapshot_location='snapshot_location_value', + ) + +def test_save_snapshot_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 = EnvironmentsClient( + 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.save_snapshot 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.save_snapshot] = mock_rpc + request = {} + client.save_snapshot(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.save_snapshot(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_save_snapshot_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 = EnvironmentsAsyncClient( + 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.save_snapshot 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.save_snapshot] = mock_rpc + + request = {} + await client.save_snapshot(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.save_snapshot(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_save_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.SaveSnapshotRequest): + client = EnvironmentsAsyncClient( + 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.save_snapshot), + '__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.save_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.SaveSnapshotRequest() + 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_save_snapshot_async_from_dict(): + await test_save_snapshot_async(request_type=dict) + +def test_save_snapshot_field_headers(): + client = EnvironmentsClient( + 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 = environments.SaveSnapshotRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.save_snapshot(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_save_snapshot_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.SaveSnapshotRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.save_snapshot(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.LoadSnapshotRequest, + dict, +]) +def test_load_snapshot(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.load_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.load_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.LoadSnapshotRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_load_snapshot_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 = EnvironmentsClient( + 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 = environments.LoadSnapshotRequest( + environment='environment_value', + snapshot_path='snapshot_path_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.load_snapshot(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.LoadSnapshotRequest( + environment='environment_value', + snapshot_path='snapshot_path_value', + ) + +def test_load_snapshot_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 = EnvironmentsClient( + 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.load_snapshot 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.load_snapshot] = mock_rpc + request = {} + client.load_snapshot(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.load_snapshot(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_load_snapshot_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 = EnvironmentsAsyncClient( + 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.load_snapshot 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.load_snapshot] = mock_rpc + + request = {} + await client.load_snapshot(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.load_snapshot(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_load_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.LoadSnapshotRequest): + client = EnvironmentsAsyncClient( + 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.load_snapshot), + '__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.load_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.LoadSnapshotRequest() + 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_load_snapshot_async_from_dict(): + await test_load_snapshot_async(request_type=dict) + +def test_load_snapshot_field_headers(): + client = EnvironmentsClient( + 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 = environments.LoadSnapshotRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.load_snapshot(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_load_snapshot_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.LoadSnapshotRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.load_snapshot(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.DatabaseFailoverRequest, + dict, +]) +def test_database_failover(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.database_failover), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.database_failover(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.DatabaseFailoverRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_database_failover_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 = EnvironmentsClient( + 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 = environments.DatabaseFailoverRequest( + environment='environment_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.database_failover(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DatabaseFailoverRequest( + environment='environment_value', + ) + +def test_database_failover_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 = EnvironmentsClient( + 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.database_failover 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.database_failover] = mock_rpc + request = {} + client.database_failover(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.database_failover(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_database_failover_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 = EnvironmentsAsyncClient( + 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.database_failover 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.database_failover] = mock_rpc + + request = {} + await client.database_failover(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.database_failover(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_database_failover_async(transport: str = 'grpc_asyncio', request_type=environments.DatabaseFailoverRequest): + client = EnvironmentsAsyncClient( + 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.database_failover), + '__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.database_failover(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.DatabaseFailoverRequest() + 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_database_failover_async_from_dict(): + await test_database_failover_async(request_type=dict) + +def test_database_failover_field_headers(): + client = EnvironmentsClient( + 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 = environments.DatabaseFailoverRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.database_failover(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_database_failover_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.DatabaseFailoverRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.database_failover(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.FetchDatabasePropertiesRequest, + dict, +]) +def test_fetch_database_properties(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.fetch_database_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.FetchDatabasePropertiesResponse( + primary_gce_zone='primary_gce_zone_value', + secondary_gce_zone='secondary_gce_zone_value', + is_failover_replica_available=True, + ) + response = client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.FetchDatabasePropertiesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.FetchDatabasePropertiesResponse) + assert response.primary_gce_zone == 'primary_gce_zone_value' + assert response.secondary_gce_zone == 'secondary_gce_zone_value' + assert response.is_failover_replica_available is True + + +def test_fetch_database_properties_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 = EnvironmentsClient( + 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 = environments.FetchDatabasePropertiesRequest( + environment='environment_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.fetch_database_properties(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.FetchDatabasePropertiesRequest( + environment='environment_value', + ) + +def test_fetch_database_properties_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 = EnvironmentsClient( + 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc + request = {} + client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_database_properties(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_fetch_database_properties_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 = EnvironmentsAsyncClient( + 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc + + request = {} + await client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_database_properties(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_fetch_database_properties_async(transport: str = 'grpc_asyncio', request_type=environments.FetchDatabasePropertiesRequest): + client = EnvironmentsAsyncClient( + 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.fetch_database_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse( + primary_gce_zone='primary_gce_zone_value', + secondary_gce_zone='secondary_gce_zone_value', + is_failover_replica_available=True, + )) + response = await client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.FetchDatabasePropertiesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.FetchDatabasePropertiesResponse) + assert response.primary_gce_zone == 'primary_gce_zone_value' + assert response.secondary_gce_zone == 'secondary_gce_zone_value' + assert response.is_failover_replica_available is True + + +@pytest.mark.asyncio +async def test_fetch_database_properties_async_from_dict(): + await test_fetch_database_properties_async(request_type=dict) + +def test_fetch_database_properties_field_headers(): + client = EnvironmentsClient( + 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 = environments.FetchDatabasePropertiesRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + call.return_value = environments.FetchDatabasePropertiesResponse() + client.fetch_database_properties(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_fetch_database_properties_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.FetchDatabasePropertiesRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse()) + await client.fetch_database_properties(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', + 'environment=environment_value', + ) in kw['metadata'] + + +def test_create_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + + request = {} + client.create_environment(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_environment(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_environment_rest_flattened(): + client = EnvironmentsClient( + 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', + environment=environments.Environment(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.create_environment(**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/*}/environments" % client.transport._host, args[1]) + + +def test_create_environment_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_environment( + environments.CreateEnvironmentRequest(), + parent='parent_value', + environment=environments.Environment(name='name_value'), + ) + + +def test_get_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + + request = {} + client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_environment(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_environment_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.Environment() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/environments/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 = environments.Environment.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_environment(**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/*/environments/*}" % client.transport._host, args[1]) + + +def test_get_environment_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_environment( + environments.GetEnvironmentRequest(), + name='name_value', + ) + + +def test_list_environments_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 = EnvironmentsClient( + 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_environments 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_environments] = mock_rpc + + request = {} + client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_environments(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_environments_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.ListEnvironmentsResponse() + + # 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 = environments.ListEnvironmentsResponse.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_environments(**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/*}/environments" % client.transport._host, args[1]) + + +def test_list_environments_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_environments( + environments.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +def test_list_environments_rest_pager(transport: str = 'rest'): + client = EnvironmentsClient( + 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 = ( + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + environments.Environment(), + ], + next_page_token='abc', + ), + environments.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + ], + next_page_token='ghi', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(environments.ListEnvironmentsResponse.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_environments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, environments.Environment) + for i in results) + + pages = list(client.list_environments(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + + request = {} + client.update_environment(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_environment(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_environment_rest_flattened(): + client = EnvironmentsClient( + 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/environments/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + environment=environments.Environment(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_environment(**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/*/environments/*}" % client.transport._host, args[1]) + + +def test_update_environment_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_environment( + environments.UpdateEnvironmentRequest(), + name='name_value', + environment=environments.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + + request = {} + client.delete_environment(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_environment(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_environment_rest_flattened(): + client = EnvironmentsClient( + 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/environments/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_environment(**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/*/environments/*}" % client.transport._host, args[1]) + + +def test_delete_environment_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_environment( + environments.DeleteEnvironmentRequest(), + name='name_value', + ) + + +def test_execute_airflow_command_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 = EnvironmentsClient( + 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc + + request = {} + client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.execute_airflow_command(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_stop_airflow_command_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 = EnvironmentsClient( + 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc + + request = {} + client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stop_airflow_command(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_poll_airflow_command_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 = EnvironmentsClient( + 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc + + request = {} + client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.poll_airflow_command(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_workloads_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 = EnvironmentsClient( + 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_workloads 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_workloads] = mock_rpc + + request = {} + client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workloads(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_workloads_rest_required_fields(request_type=environments.ListWorkloadsRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_workloads._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_workloads._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.ListWorkloadsResponse() + # 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 = environments.ListWorkloadsResponse.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_workloads(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workloads_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workloads._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_workloads_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.ListWorkloadsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListWorkloadsResponse.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_workloads(**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/*/environments/*}/workloads" % client.transport._host, args[1]) + + +def test_list_workloads_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_workloads( + environments.ListWorkloadsRequest(), + parent='parent_value', + ) + + +def test_list_workloads_rest_pager(transport: str = 'rest'): + client = EnvironmentsClient( + 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 = ( + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='abc', + ), + environments.ListWorkloadsResponse( + workloads=[], + next_page_token='def', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='ghi', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(environments.ListWorkloadsResponse.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/environments/sample3'} + + pager = client.list_workloads(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, environments.ListWorkloadsResponse.ComposerWorkload) + for i in results) + + pages = list(client.list_workloads(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_check_upgrade_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 = EnvironmentsClient( + 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.check_upgrade 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.check_upgrade] = mock_rpc + + request = {} + client.check_upgrade(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.check_upgrade(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_check_upgrade_rest_required_fields(request_type=environments.CheckUpgradeRequest): + transport_class = transports.EnvironmentsRestTransport + + request_init = {} + request_init["environment"] = "" + 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()).check_upgrade._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["environment"] = 'environment_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).check_upgrade._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "environment" in jsonified_request + assert jsonified_request["environment"] == 'environment_value' + + client = EnvironmentsClient( + 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.check_upgrade(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_check_upgrade_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.check_upgrade._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("environment", ))) + + +def test_create_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.CreateUserWorkloadsSecretRequest): + transport_class = transports.EnvironmentsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_secret._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_secret._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.UserWorkloadsSecret() + # 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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_user_workloads_secret_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_user_workloads_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "userWorkloadsSecret", ))) + + +def test_create_user_workloads_secret_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(**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/*/environments/*}/userWorkloadsSecrets" % client.transport._host, args[1]) + + +def test_create_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.CreateUserWorkloadsSecretRequest(), + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + + +def test_get_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.GetUserWorkloadsSecretRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_secret._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_user_workloads_secret._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.UserWorkloadsSecret() + # 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 = environments.UserWorkloadsSecret.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_user_workloads_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_user_workloads_secret_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_user_workloads_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_user_workloads_secret_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = environments.UserWorkloadsSecret.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_user_workloads_secret(**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/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) + + +def test_get_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.GetUserWorkloadsSecretRequest(), + name='name_value', + ) + + +def test_list_user_workloads_secrets_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 = EnvironmentsClient( + 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc + + request = {} + client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_user_workloads_secrets(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_user_workloads_secrets_rest_required_fields(request_type=environments.ListUserWorkloadsSecretsRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_secrets._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_user_workloads_secrets._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.ListUserWorkloadsSecretsResponse() + # 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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_user_workloads_secrets_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_user_workloads_secrets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_user_workloads_secrets_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.ListUserWorkloadsSecretsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(**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/*/environments/*}/userWorkloadsSecrets" % client.transport._host, args[1]) + + +def test_list_user_workloads_secrets_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_secrets( + environments.ListUserWorkloadsSecretsRequest(), + parent='parent_value', + ) + + +def test_list_user_workloads_secrets_rest_pager(transport: str = 'rest'): + client = EnvironmentsClient( + 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 = ( + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[], + next_page_token='def', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(environments.ListUserWorkloadsSecretsResponse.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/environments/sample3'} + + pager = client.list_user_workloads_secrets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, environments.UserWorkloadsSecret) + for i in results) + + pages = list(client.list_user_workloads_secrets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_workloads_secret(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_user_workloads_secret_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + user_workloads_secret=environments.UserWorkloadsSecret(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 = environments.UserWorkloadsSecret.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.update_user_workloads_secret(**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/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) + + +def test_update_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.UpdateUserWorkloadsSecretRequest(), + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + + +def test_delete_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.DeleteUserWorkloadsSecretRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_secret._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_user_workloads_secret._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = '' + + response_value._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_user_workloads_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_user_workloads_secret_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_user_workloads_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_user_workloads_secret_rest_flattened(): + client = EnvironmentsClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = '' + response_value._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_user_workloads_secret(**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/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) + + +def test_delete_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.DeleteUserWorkloadsSecretRequest(), + name='name_value', + ) + + +def test_create_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.CreateUserWorkloadsConfigMapRequest): + transport_class = transports.EnvironmentsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_config_map._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_config_map._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.UserWorkloadsConfigMap() + # 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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_user_workloads_config_map_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_user_workloads_config_map._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "userWorkloadsConfigMap", ))) + + +def test_create_user_workloads_config_map_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsConfigMap() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(**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/*/environments/*}/userWorkloadsConfigMaps" % client.transport._host, args[1]) + + +def test_create_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.CreateUserWorkloadsConfigMapRequest(), + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + + +def test_get_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.GetUserWorkloadsConfigMapRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_config_map._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_user_workloads_config_map._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.UserWorkloadsConfigMap() + # 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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_user_workloads_config_map_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_user_workloads_config_map._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_user_workloads_config_map_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsConfigMap() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(**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/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) + + +def test_get_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.GetUserWorkloadsConfigMapRequest(), + name='name_value', + ) + + +def test_list_user_workloads_config_maps_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 = EnvironmentsClient( + 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc + + request = {} + client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_user_workloads_config_maps(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_user_workloads_config_maps_rest_required_fields(request_type=environments.ListUserWorkloadsConfigMapsRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_config_maps._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_user_workloads_config_maps._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.ListUserWorkloadsConfigMapsResponse() + # 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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_user_workloads_config_maps_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_user_workloads_config_maps._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_user_workloads_config_maps_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.ListUserWorkloadsConfigMapsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(**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/*/environments/*}/userWorkloadsConfigMaps" % client.transport._host, args[1]) + + +def test_list_user_workloads_config_maps_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_config_maps( + environments.ListUserWorkloadsConfigMapsRequest(), + parent='parent_value', + ) + + +def test_list_user_workloads_config_maps_rest_pager(transport: str = 'rest'): + client = EnvironmentsClient( + 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 = ( + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[], + next_page_token='def', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(environments.ListUserWorkloadsConfigMapsResponse.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/environments/sample3'} + + pager = client.list_user_workloads_config_maps(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, environments.UserWorkloadsConfigMap) + for i in results) + + pages = list(client.list_user_workloads_config_maps(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_workloads_config_map(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_user_workloads_config_map_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsConfigMap() + + # get arguments that satisfy an http rule for this method + sample_request = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + user_workloads_config_map=environments.UserWorkloadsConfigMap(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 = environments.UserWorkloadsConfigMap.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.update_user_workloads_config_map(**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/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) + + +def test_update_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.UpdateUserWorkloadsConfigMapRequest(), + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + + +def test_delete_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.DeleteUserWorkloadsConfigMapRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_config_map._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_user_workloads_config_map._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = '' + + response_value._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_user_workloads_config_map(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_user_workloads_config_map_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_user_workloads_config_map._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_user_workloads_config_map_rest_flattened(): + client = EnvironmentsClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = '' + response_value._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_user_workloads_config_map(**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/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) + + +def test_delete_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.DeleteUserWorkloadsConfigMapRequest(), + name='name_value', + ) + + +def test_save_snapshot_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 = EnvironmentsClient( + 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.save_snapshot 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.save_snapshot] = mock_rpc + + request = {} + client.save_snapshot(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.save_snapshot(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_load_snapshot_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 = EnvironmentsClient( + 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.load_snapshot 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.load_snapshot] = mock_rpc + + request = {} + client.load_snapshot(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.load_snapshot(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_database_failover_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 = EnvironmentsClient( + 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.database_failover 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.database_failover] = mock_rpc + + request = {} + client.database_failover(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.database_failover(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_fetch_database_properties_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 = EnvironmentsClient( + 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc + + request = {} + client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_database_properties(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_fetch_database_properties_rest_required_fields(request_type=environments.FetchDatabasePropertiesRequest): + transport_class = transports.EnvironmentsRestTransport + + request_init = {} + request_init["environment"] = "" + 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()).fetch_database_properties._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["environment"] = 'environment_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_database_properties._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "environment" in jsonified_request + assert jsonified_request["environment"] == 'environment_value' + + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.FetchDatabasePropertiesResponse() + # 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 = environments.FetchDatabasePropertiesResponse.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.fetch_database_properties(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_fetch_database_properties_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.fetch_database_properties._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("environment", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EnvironmentsClient( + 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 = EnvironmentsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EnvironmentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EnvironmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + transports.EnvironmentsRestTransport, +]) +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 = EnvironmentsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = EnvironmentsClient( + 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_environment_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateEnvironmentRequest() + + 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_environment_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value = environments.Environment() + client.get_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetEnvironmentRequest() + + 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_environments_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value = environments.ListEnvironmentsResponse() + client.list_environments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListEnvironmentsRequest() + + 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_environment_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateEnvironmentRequest() + + 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_environment_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteEnvironmentRequest() + + 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_execute_airflow_command_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + call.return_value = environments.ExecuteAirflowCommandResponse() + client.execute_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ExecuteAirflowCommandRequest() + + 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_stop_airflow_command_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + call.return_value = environments.StopAirflowCommandResponse() + client.stop_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.StopAirflowCommandRequest() + + 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_poll_airflow_command_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + call.return_value = environments.PollAirflowCommandResponse() + client.poll_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.PollAirflowCommandRequest() + + 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_workloads_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + call.return_value = environments.ListWorkloadsResponse() + client.list_workloads(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListWorkloadsRequest() + + 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_check_upgrade_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.check_upgrade(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CheckUpgradeRequest() + + 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_user_workloads_secret_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.create_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.get_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsSecretRequest() + + 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_user_workloads_secrets_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + call.return_value = environments.ListUserWorkloadsSecretsResponse() + client.list_user_workloads_secrets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsSecretsRequest() + + 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_user_workloads_secret_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.update_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + call.return_value = None + client.delete_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsSecretRequest() + + 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_user_workloads_config_map_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.create_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.get_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_maps_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + call.return_value = environments.ListUserWorkloadsConfigMapsResponse() + client.list_user_workloads_config_maps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsConfigMapsRequest() + + 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_user_workloads_config_map_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.update_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + call.return_value = None + client.delete_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsConfigMapRequest() + + 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_save_snapshot_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.save_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.SaveSnapshotRequest() + + 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_load_snapshot_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.load_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.LoadSnapshotRequest() + + 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_database_failover_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.database_failover(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DatabaseFailoverRequest() + + 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_fetch_database_properties_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + call.return_value = environments.FetchDatabasePropertiesResponse() + client.fetch_database_properties(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.FetchDatabasePropertiesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = EnvironmentsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = EnvironmentsAsyncClient( + 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_environment_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__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_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateEnvironmentRequest() + + 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_environment_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment( + name='name_value', + uuid='uuid_value', + state=environments.Environment.State.CREATING, + satisfies_pzs=True, + satisfies_pzi=True, + )) + await client.get_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetEnvironmentRequest() + + 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_environments_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse( + next_page_token='next_page_token_value', + )) + await client.list_environments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListEnvironmentsRequest() + + 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_environment_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__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_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateEnvironmentRequest() + + 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_environment_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__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_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteEnvironmentRequest() + + 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_execute_airflow_command_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse( + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + error='error_value', + )) + await client.execute_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ExecuteAirflowCommandRequest() + + 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_stop_airflow_command_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse( + is_done=True, + output=['output_value'], + )) + await client.stop_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.StopAirflowCommandRequest() + + 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_poll_airflow_command_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse( + output_end=True, + )) + await client.poll_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.PollAirflowCommandRequest() + + 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_workloads_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse( + next_page_token='next_page_token_value', + )) + await client.list_workloads(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListWorkloadsRequest() + + 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_check_upgrade_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__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.check_upgrade(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CheckUpgradeRequest() + + 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_user_workloads_secret_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + await client.create_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + await client.get_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsSecretRequest() + + 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_user_workloads_secrets_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse( + next_page_token='next_page_token_value', + )) + await client.list_user_workloads_secrets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsSecretsRequest() + + 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_user_workloads_secret_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + await client.update_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsSecretRequest() + + 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_user_workloads_config_map_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + await client.create_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + await client.get_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_maps_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse( + next_page_token='next_page_token_value', + )) + await client.list_user_workloads_config_maps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsConfigMapsRequest() + + 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_user_workloads_config_map_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + await client.update_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsConfigMapRequest() + + 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_save_snapshot_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__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.save_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.SaveSnapshotRequest() + + 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_load_snapshot_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__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.load_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.LoadSnapshotRequest() + + 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_database_failover_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__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.database_failover(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DatabaseFailoverRequest() + + 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_fetch_database_properties_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse( + primary_gce_zone='primary_gce_zone_value', + secondary_gce_zone='secondary_gce_zone_value', + is_failover_replica_available=True, + )) + await client.fetch_database_properties(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.FetchDatabasePropertiesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = EnvironmentsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_environment_rest_bad_request(request_type=environments.CreateEnvironmentRequest): + client = EnvironmentsClient( + 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_environment(request) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateEnvironmentRequest, + dict, +]) +def test_create_environment_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["environment"] = {'name': 'name_value', 'config': {'gke_cluster': 'gke_cluster_value', 'dag_gcs_prefix': 'dag_gcs_prefix_value', 'node_count': 1070, 'software_config': {'image_version': 'image_version_value', 'airflow_config_overrides': {}, 'pypi_packages': {}, 'env_variables': {}, 'python_version': 'python_version_value', 'scheduler_count': 1607, 'cloud_data_lineage_integration': {'enabled': True}, 'web_server_plugins_mode': 1}, 'node_config': {'location': 'location_value', 'machine_type': 'machine_type_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'disk_size_gb': 1261, 'oauth_scopes': ['oauth_scopes_value1', 'oauth_scopes_value2'], 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'ip_allocation_policy': {'use_ip_aliases': True, 'cluster_secondary_range_name': 'cluster_secondary_range_name_value', 'cluster_ipv4_cidr_block': 'cluster_ipv4_cidr_block_value', 'services_secondary_range_name': 'services_secondary_range_name_value', 'services_ipv4_cidr_block': 'services_ipv4_cidr_block_value'}, 'enable_ip_masq_agent': True, 'composer_network_attachment': 'composer_network_attachment_value', 'composer_internal_ipv4_cidr_block': 'composer_internal_ipv4_cidr_block_value'}, 'private_environment_config': {'enable_private_environment': True, 'enable_private_builds_only': True, 'private_cluster_config': {'enable_private_endpoint': True, 'master_ipv4_cidr_block': 'master_ipv4_cidr_block_value', 'master_ipv4_reserved_range': 'master_ipv4_reserved_range_value'}, 'web_server_ipv4_cidr_block': 'web_server_ipv4_cidr_block_value', 'cloud_sql_ipv4_cidr_block': 'cloud_sql_ipv4_cidr_block_value', 'web_server_ipv4_reserved_range': 'web_server_ipv4_reserved_range_value', 'cloud_composer_network_ipv4_cidr_block': 'cloud_composer_network_ipv4_cidr_block_value', 'cloud_composer_network_ipv4_reserved_range': 'cloud_composer_network_ipv4_reserved_range_value', 'enable_privately_used_public_ips': True, 'cloud_composer_connection_subnetwork': 'cloud_composer_connection_subnetwork_value', 'networking_config': {'connection_type': 1}}, 'web_server_network_access_control': {'allowed_ip_ranges': [{'value': 'value_value', 'description': 'description_value'}]}, 'database_config': {'machine_type': 'machine_type_value', 'zone': 'zone_value'}, 'web_server_config': {'machine_type': 'machine_type_value'}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'maintenance_window': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'recurrence': 'recurrence_value'}, 'workloads_config': {'scheduler': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}, 'web_server': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053}, 'worker': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'min_count': 972, 'max_count': 974}, 'triggerer': {'count': 553, 'cpu': 0.328, 'memory_gb': 0.961}, 'dag_processor': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}}, 'environment_size': 1, 'airflow_uri': 'airflow_uri_value', 'airflow_byoid_uri': 'airflow_byoid_uri_value', 'master_authorized_networks_config': {'enabled': True, 'cidr_blocks': [{'display_name': 'display_name_value', 'cidr_block': 'cidr_block_value'}]}, 'recovery_config': {'scheduled_snapshots_config': {'enabled': True, 'snapshot_location': 'snapshot_location_value', 'snapshot_creation_schedule': 'snapshot_creation_schedule_value', 'time_zone': 'time_zone_value'}}, 'resilience_mode': 1, 'data_retention_config': {'airflow_metadata_retention_config': {'retention_mode': 1, 'retention_days': 1512}, 'task_logs_retention_config': {'storage_mode': 1}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': True, 'satisfies_pzi': True, 'storage_config': {'bucket': 'bucket_value'}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = environments.CreateEnvironmentRequest.meta.fields["environment"] + + 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["environment"].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["environment"][field])): + del request_init["environment"][field][i][subfield] + else: + del request_init["environment"][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_environment(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_environment_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_environment") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_environment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_environment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.CreateEnvironmentRequest.pb(environments.CreateEnvironmentRequest()) + 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 = environments.CreateEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_environment_rest_bad_request(request_type=environments.GetEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) + + +@pytest.mark.parametrize("request_type", [ + environments.GetEnvironmentRequest, + dict, +]) +def test_get_environment_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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 = environments.Environment( + name='name_value', + uuid='uuid_value', + state=environments.Environment.State.CREATING, + satisfies_pzs=True, + satisfies_pzi=True, + ) + + # 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 = environments.Environment.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_environment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.Environment) + assert response.name == 'name_value' + assert response.uuid == 'uuid_value' + assert response.state == environments.Environment.State.CREATING + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_environment_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_environment") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_environment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_environment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.GetEnvironmentRequest.pb(environments.GetEnvironmentRequest()) + 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 = environments.Environment.to_json(environments.Environment()) + req.return_value.content = return_value + + request = environments.GetEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.Environment() + post_with_metadata.return_value = environments.Environment(), metadata + + client.get_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_environments_rest_bad_request(request_type=environments.ListEnvironmentsRequest): + client = EnvironmentsClient( + 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_environments(request) + + +@pytest.mark.parametrize("request_type", [ + environments.ListEnvironmentsRequest, + dict, +]) +def test_list_environments_rest_call_success(request_type): + client = EnvironmentsClient( + 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 = environments.ListEnvironmentsResponse( + 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 = environments.ListEnvironmentsResponse.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_environments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnvironmentsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_environments_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_environments") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_environments_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_environments") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.ListEnvironmentsRequest.pb(environments.ListEnvironmentsRequest()) + 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 = environments.ListEnvironmentsResponse.to_json(environments.ListEnvironmentsResponse()) + req.return_value.content = return_value + + request = environments.ListEnvironmentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListEnvironmentsResponse() + post_with_metadata.return_value = environments.ListEnvironmentsResponse(), metadata + + client.list_environments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_environment_rest_bad_request(request_type=environments.UpdateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateEnvironmentRequest, + dict, +]) +def test_update_environment_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3'} + request_init["environment"] = {'name': 'name_value', 'config': {'gke_cluster': 'gke_cluster_value', 'dag_gcs_prefix': 'dag_gcs_prefix_value', 'node_count': 1070, 'software_config': {'image_version': 'image_version_value', 'airflow_config_overrides': {}, 'pypi_packages': {}, 'env_variables': {}, 'python_version': 'python_version_value', 'scheduler_count': 1607, 'cloud_data_lineage_integration': {'enabled': True}, 'web_server_plugins_mode': 1}, 'node_config': {'location': 'location_value', 'machine_type': 'machine_type_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'disk_size_gb': 1261, 'oauth_scopes': ['oauth_scopes_value1', 'oauth_scopes_value2'], 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'ip_allocation_policy': {'use_ip_aliases': True, 'cluster_secondary_range_name': 'cluster_secondary_range_name_value', 'cluster_ipv4_cidr_block': 'cluster_ipv4_cidr_block_value', 'services_secondary_range_name': 'services_secondary_range_name_value', 'services_ipv4_cidr_block': 'services_ipv4_cidr_block_value'}, 'enable_ip_masq_agent': True, 'composer_network_attachment': 'composer_network_attachment_value', 'composer_internal_ipv4_cidr_block': 'composer_internal_ipv4_cidr_block_value'}, 'private_environment_config': {'enable_private_environment': True, 'enable_private_builds_only': True, 'private_cluster_config': {'enable_private_endpoint': True, 'master_ipv4_cidr_block': 'master_ipv4_cidr_block_value', 'master_ipv4_reserved_range': 'master_ipv4_reserved_range_value'}, 'web_server_ipv4_cidr_block': 'web_server_ipv4_cidr_block_value', 'cloud_sql_ipv4_cidr_block': 'cloud_sql_ipv4_cidr_block_value', 'web_server_ipv4_reserved_range': 'web_server_ipv4_reserved_range_value', 'cloud_composer_network_ipv4_cidr_block': 'cloud_composer_network_ipv4_cidr_block_value', 'cloud_composer_network_ipv4_reserved_range': 'cloud_composer_network_ipv4_reserved_range_value', 'enable_privately_used_public_ips': True, 'cloud_composer_connection_subnetwork': 'cloud_composer_connection_subnetwork_value', 'networking_config': {'connection_type': 1}}, 'web_server_network_access_control': {'allowed_ip_ranges': [{'value': 'value_value', 'description': 'description_value'}]}, 'database_config': {'machine_type': 'machine_type_value', 'zone': 'zone_value'}, 'web_server_config': {'machine_type': 'machine_type_value'}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'maintenance_window': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'recurrence': 'recurrence_value'}, 'workloads_config': {'scheduler': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}, 'web_server': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053}, 'worker': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'min_count': 972, 'max_count': 974}, 'triggerer': {'count': 553, 'cpu': 0.328, 'memory_gb': 0.961}, 'dag_processor': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}}, 'environment_size': 1, 'airflow_uri': 'airflow_uri_value', 'airflow_byoid_uri': 'airflow_byoid_uri_value', 'master_authorized_networks_config': {'enabled': True, 'cidr_blocks': [{'display_name': 'display_name_value', 'cidr_block': 'cidr_block_value'}]}, 'recovery_config': {'scheduled_snapshots_config': {'enabled': True, 'snapshot_location': 'snapshot_location_value', 'snapshot_creation_schedule': 'snapshot_creation_schedule_value', 'time_zone': 'time_zone_value'}}, 'resilience_mode': 1, 'data_retention_config': {'airflow_metadata_retention_config': {'retention_mode': 1, 'retention_days': 1512}, 'task_logs_retention_config': {'storage_mode': 1}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': True, 'satisfies_pzi': True, 'storage_config': {'bucket': 'bucket_value'}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = environments.UpdateEnvironmentRequest.meta.fields["environment"] + + 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["environment"].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["environment"][field])): + del request_init["environment"][field][i][subfield] + else: + del request_init["environment"][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_environment(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_environment_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_environment") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_environment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_environment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.UpdateEnvironmentRequest.pb(environments.UpdateEnvironmentRequest()) + 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 = environments.UpdateEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_environment_rest_bad_request(request_type=environments.DeleteEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteEnvironmentRequest, + dict, +]) +def test_delete_environment_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(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_environment_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_delete_environment") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_delete_environment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_delete_environment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.DeleteEnvironmentRequest.pb(environments.DeleteEnvironmentRequest()) + 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 = environments.DeleteEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_execute_airflow_command_rest_bad_request(request_type=environments.ExecuteAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.execute_airflow_command(request) + + +@pytest.mark.parametrize("request_type", [ + environments.ExecuteAirflowCommandRequest, + dict, +]) +def test_execute_airflow_command_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.ExecuteAirflowCommandResponse( + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + error='error_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 = environments.ExecuteAirflowCommandResponse.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.execute_airflow_command(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.ExecuteAirflowCommandResponse) + assert response.execution_id == 'execution_id_value' + assert response.pod == 'pod_value' + assert response.pod_namespace == 'pod_namespace_value' + assert response.error == 'error_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_execute_airflow_command_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_execute_airflow_command") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_execute_airflow_command_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_execute_airflow_command") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.ExecuteAirflowCommandRequest.pb(environments.ExecuteAirflowCommandRequest()) + 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 = environments.ExecuteAirflowCommandResponse.to_json(environments.ExecuteAirflowCommandResponse()) + req.return_value.content = return_value + + request = environments.ExecuteAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ExecuteAirflowCommandResponse() + post_with_metadata.return_value = environments.ExecuteAirflowCommandResponse(), metadata + + client.execute_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_stop_airflow_command_rest_bad_request(request_type=environments.StopAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.stop_airflow_command(request) + + +@pytest.mark.parametrize("request_type", [ + environments.StopAirflowCommandRequest, + dict, +]) +def test_stop_airflow_command_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.StopAirflowCommandResponse( + is_done=True, + output=['output_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 = environments.StopAirflowCommandResponse.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.stop_airflow_command(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ['output_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_airflow_command_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_stop_airflow_command") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_stop_airflow_command_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_stop_airflow_command") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.StopAirflowCommandRequest.pb(environments.StopAirflowCommandRequest()) + 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 = environments.StopAirflowCommandResponse.to_json(environments.StopAirflowCommandResponse()) + req.return_value.content = return_value + + request = environments.StopAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.StopAirflowCommandResponse() + post_with_metadata.return_value = environments.StopAirflowCommandResponse(), metadata + + client.stop_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_poll_airflow_command_rest_bad_request(request_type=environments.PollAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.poll_airflow_command(request) + + +@pytest.mark.parametrize("request_type", [ + environments.PollAirflowCommandRequest, + dict, +]) +def test_poll_airflow_command_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.PollAirflowCommandResponse( + output_end=True, + ) + + # 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 = environments.PollAirflowCommandResponse.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.poll_airflow_command(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.PollAirflowCommandResponse) + assert response.output_end is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_poll_airflow_command_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_poll_airflow_command") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_poll_airflow_command_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_poll_airflow_command") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.PollAirflowCommandRequest.pb(environments.PollAirflowCommandRequest()) + 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 = environments.PollAirflowCommandResponse.to_json(environments.PollAirflowCommandResponse()) + req.return_value.content = return_value + + request = environments.PollAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.PollAirflowCommandResponse() + post_with_metadata.return_value = environments.PollAirflowCommandResponse(), metadata + + client.poll_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_workloads_rest_bad_request(request_type=environments.ListWorkloadsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_workloads(request) + + +@pytest.mark.parametrize("request_type", [ + environments.ListWorkloadsRequest, + dict, +]) +def test_list_workloads_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListWorkloadsResponse( + 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 = environments.ListWorkloadsResponse.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_workloads(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workloads_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_workloads") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_workloads_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_workloads") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.ListWorkloadsRequest.pb(environments.ListWorkloadsRequest()) + 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 = environments.ListWorkloadsResponse.to_json(environments.ListWorkloadsResponse()) + req.return_value.content = return_value + + request = environments.ListWorkloadsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListWorkloadsResponse() + post_with_metadata.return_value = environments.ListWorkloadsResponse(), metadata + + client.list_workloads(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_check_upgrade_rest_bad_request(request_type=environments.CheckUpgradeRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.check_upgrade(request) + + +@pytest.mark.parametrize("request_type", [ + environments.CheckUpgradeRequest, + dict, +]) +def test_check_upgrade_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.check_upgrade(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_check_upgrade_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_check_upgrade") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_check_upgrade_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_check_upgrade") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.CheckUpgradeRequest.pb(environments.CheckUpgradeRequest()) + 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 = environments.CheckUpgradeRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.check_upgrade(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_user_workloads_secret_rest_bad_request(request_type=environments.CreateUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_secret(request) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsSecretRequest, + dict, +]) +def test_create_user_workloads_secret_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} + request_init["user_workloads_secret"] = {'name': 'name_value', 'data': {}} + # 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 = environments.CreateUserWorkloadsSecretRequest.meta.fields["user_workloads_secret"] + + 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["user_workloads_secret"].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["user_workloads_secret"][field])): + del request_init["user_workloads_secret"][field][i][subfield] + else: + del request_init["user_workloads_secret"][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 = environments.UserWorkloadsSecret( + 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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_workloads_secret_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_user_workloads_secret") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_user_workloads_secret_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_user_workloads_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.CreateUserWorkloadsSecretRequest.pb(environments.CreateUserWorkloadsSecretRequest()) + 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + req.return_value.content = return_value + + request = environments.CreateUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata + + client.create_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_user_workloads_secret_rest_bad_request(request_type=environments.GetUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsSecretRequest, + dict, +]) +def test_get_user_workloads_secret_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = environments.UserWorkloadsSecret( + 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 = environments.UserWorkloadsSecret.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_user_workloads_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_workloads_secret_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_user_workloads_secret") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_user_workloads_secret_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_user_workloads_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.GetUserWorkloadsSecretRequest.pb(environments.GetUserWorkloadsSecretRequest()) + 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + req.return_value.content = return_value + + request = environments.GetUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata + + client.get_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_user_workloads_secrets_rest_bad_request(request_type=environments.ListUserWorkloadsSecretsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_secrets(request) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsSecretsRequest, + dict, +]) +def test_list_user_workloads_secrets_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsSecretsResponse( + 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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsSecretsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_user_workloads_secrets_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_user_workloads_secrets") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_user_workloads_secrets_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_user_workloads_secrets") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.ListUserWorkloadsSecretsRequest.pb(environments.ListUserWorkloadsSecretsRequest()) + 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 = environments.ListUserWorkloadsSecretsResponse.to_json(environments.ListUserWorkloadsSecretsResponse()) + req.return_value.content = return_value + + request = environments.ListUserWorkloadsSecretsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListUserWorkloadsSecretsResponse() + post_with_metadata.return_value = environments.ListUserWorkloadsSecretsResponse(), metadata + + client.list_user_workloads_secrets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_user_workloads_secret_rest_bad_request(request_type=environments.UpdateUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateUserWorkloadsSecretRequest, + dict, +]) +def test_update_user_workloads_secret_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4'}} + request_init["user_workloads_secret"] = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4', 'data': {}} + # 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 = environments.UpdateUserWorkloadsSecretRequest.meta.fields["user_workloads_secret"] + + 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["user_workloads_secret"].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["user_workloads_secret"][field])): + del request_init["user_workloads_secret"][field][i][subfield] + else: + del request_init["user_workloads_secret"][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 = environments.UserWorkloadsSecret( + 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 = environments.UserWorkloadsSecret.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.update_user_workloads_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_workloads_secret_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_user_workloads_secret") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_user_workloads_secret_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_user_workloads_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.UpdateUserWorkloadsSecretRequest.pb(environments.UpdateUserWorkloadsSecretRequest()) + 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + req.return_value.content = return_value + + request = environments.UpdateUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata + + client.update_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_user_workloads_secret_rest_bad_request(request_type=environments.DeleteUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsSecretRequest, + dict, +]) +def test_delete_user_workloads_secret_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = 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_user_workloads_secret(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_user_workloads_secret_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "pre_delete_user_workloads_secret") as pre: + pre.assert_not_called() + pb_message = environments.DeleteUserWorkloadsSecretRequest.pb(environments.DeleteUserWorkloadsSecretRequest()) + 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"} + + request = environments.DeleteUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_create_user_workloads_config_map_rest_bad_request(request_type=environments.CreateUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_config_map(request) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsConfigMapRequest, + dict, +]) +def test_create_user_workloads_config_map_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} + request_init["user_workloads_config_map"] = {'name': 'name_value', 'data': {}} + # 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 = environments.CreateUserWorkloadsConfigMapRequest.meta.fields["user_workloads_config_map"] + + 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["user_workloads_config_map"].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["user_workloads_config_map"][field])): + del request_init["user_workloads_config_map"][field][i][subfield] + else: + del request_init["user_workloads_config_map"][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 = environments.UserWorkloadsConfigMap( + 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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_workloads_config_map_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_user_workloads_config_map") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_user_workloads_config_map_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_user_workloads_config_map") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.CreateUserWorkloadsConfigMapRequest.pb(environments.CreateUserWorkloadsConfigMapRequest()) + 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + req.return_value.content = return_value + + request = environments.CreateUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata + + client.create_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_user_workloads_config_map_rest_bad_request(request_type=environments.GetUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsConfigMapRequest, + dict, +]) +def test_get_user_workloads_config_map_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = environments.UserWorkloadsConfigMap( + 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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_workloads_config_map_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_user_workloads_config_map") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_user_workloads_config_map_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_user_workloads_config_map") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.GetUserWorkloadsConfigMapRequest.pb(environments.GetUserWorkloadsConfigMapRequest()) + 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + req.return_value.content = return_value + + request = environments.GetUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata + + client.get_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_user_workloads_config_maps_rest_bad_request(request_type=environments.ListUserWorkloadsConfigMapsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_config_maps(request) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsConfigMapsRequest, + dict, +]) +def test_list_user_workloads_config_maps_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsConfigMapsResponse( + 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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsConfigMapsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_user_workloads_config_maps_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_user_workloads_config_maps") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_user_workloads_config_maps_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_user_workloads_config_maps") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.ListUserWorkloadsConfigMapsRequest.pb(environments.ListUserWorkloadsConfigMapsRequest()) + 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 = environments.ListUserWorkloadsConfigMapsResponse.to_json(environments.ListUserWorkloadsConfigMapsResponse()) + req.return_value.content = return_value + + request = environments.ListUserWorkloadsConfigMapsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListUserWorkloadsConfigMapsResponse() + post_with_metadata.return_value = environments.ListUserWorkloadsConfigMapsResponse(), metadata + + client.list_user_workloads_config_maps(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_user_workloads_config_map_rest_bad_request(request_type=environments.UpdateUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateUserWorkloadsConfigMapRequest, + dict, +]) +def test_update_user_workloads_config_map_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4'}} + request_init["user_workloads_config_map"] = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4', 'data': {}} + # 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 = environments.UpdateUserWorkloadsConfigMapRequest.meta.fields["user_workloads_config_map"] + + 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["user_workloads_config_map"].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["user_workloads_config_map"][field])): + del request_init["user_workloads_config_map"][field][i][subfield] + else: + del request_init["user_workloads_config_map"][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 = environments.UserWorkloadsConfigMap( + 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 = environments.UserWorkloadsConfigMap.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.update_user_workloads_config_map(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_workloads_config_map_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_user_workloads_config_map") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_user_workloads_config_map_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_user_workloads_config_map") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.UpdateUserWorkloadsConfigMapRequest.pb(environments.UpdateUserWorkloadsConfigMapRequest()) + 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + req.return_value.content = return_value + + request = environments.UpdateUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata + + client.update_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_user_workloads_config_map_rest_bad_request(request_type=environments.DeleteUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsConfigMapRequest, + dict, +]) +def test_delete_user_workloads_config_map_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = 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_user_workloads_config_map(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_user_workloads_config_map_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "pre_delete_user_workloads_config_map") as pre: + pre.assert_not_called() + pb_message = environments.DeleteUserWorkloadsConfigMapRequest.pb(environments.DeleteUserWorkloadsConfigMapRequest()) + 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"} + + request = environments.DeleteUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_save_snapshot_rest_bad_request(request_type=environments.SaveSnapshotRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.save_snapshot(request) + + +@pytest.mark.parametrize("request_type", [ + environments.SaveSnapshotRequest, + dict, +]) +def test_save_snapshot_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.save_snapshot(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_save_snapshot_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_save_snapshot") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_save_snapshot_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_save_snapshot") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.SaveSnapshotRequest.pb(environments.SaveSnapshotRequest()) + 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 = environments.SaveSnapshotRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.save_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_load_snapshot_rest_bad_request(request_type=environments.LoadSnapshotRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.load_snapshot(request) + + +@pytest.mark.parametrize("request_type", [ + environments.LoadSnapshotRequest, + dict, +]) +def test_load_snapshot_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.load_snapshot(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_load_snapshot_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_load_snapshot") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_load_snapshot_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_load_snapshot") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.LoadSnapshotRequest.pb(environments.LoadSnapshotRequest()) + 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 = environments.LoadSnapshotRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.load_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_database_failover_rest_bad_request(request_type=environments.DatabaseFailoverRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.database_failover(request) + + +@pytest.mark.parametrize("request_type", [ + environments.DatabaseFailoverRequest, + dict, +]) +def test_database_failover_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.database_failover(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_database_failover_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_database_failover") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_database_failover_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_database_failover") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.DatabaseFailoverRequest.pb(environments.DatabaseFailoverRequest()) + 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 = environments.DatabaseFailoverRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.database_failover(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_fetch_database_properties_rest_bad_request(request_type=environments.FetchDatabasePropertiesRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.fetch_database_properties(request) + + +@pytest.mark.parametrize("request_type", [ + environments.FetchDatabasePropertiesRequest, + dict, +]) +def test_fetch_database_properties_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.FetchDatabasePropertiesResponse( + primary_gce_zone='primary_gce_zone_value', + secondary_gce_zone='secondary_gce_zone_value', + is_failover_replica_available=True, + ) + + # 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 = environments.FetchDatabasePropertiesResponse.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.fetch_database_properties(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.FetchDatabasePropertiesResponse) + assert response.primary_gce_zone == 'primary_gce_zone_value' + assert response.secondary_gce_zone == 'secondary_gce_zone_value' + assert response.is_failover_replica_available is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_database_properties_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_fetch_database_properties") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_fetch_database_properties_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_fetch_database_properties") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.FetchDatabasePropertiesRequest.pb(environments.FetchDatabasePropertiesRequest()) + 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 = environments.FetchDatabasePropertiesResponse.to_json(environments.FetchDatabasePropertiesResponse()) + req.return_value.content = return_value + + request = environments.FetchDatabasePropertiesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.FetchDatabasePropertiesResponse() + post_with_metadata.return_value = environments.FetchDatabasePropertiesResponse(), metadata + + client.fetch_database_properties(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = EnvironmentsClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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_environment_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + client.create_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateEnvironmentRequest() + + 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_environment_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + client.get_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetEnvironmentRequest() + + 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_environments_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + client.list_environments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListEnvironmentsRequest() + + 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_environment_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + client.update_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateEnvironmentRequest() + + 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_environment_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + client.delete_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteEnvironmentRequest() + + 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_execute_airflow_command_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + client.execute_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ExecuteAirflowCommandRequest() + + 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_stop_airflow_command_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + client.stop_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.StopAirflowCommandRequest() + + 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_poll_airflow_command_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + client.poll_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.PollAirflowCommandRequest() + + 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_workloads_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + client.list_workloads(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListWorkloadsRequest() + + 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_check_upgrade_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + client.check_upgrade(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CheckUpgradeRequest() + + 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_user_workloads_secret_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + client.create_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + client.get_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsSecretRequest() + + 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_user_workloads_secrets_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + client.list_user_workloads_secrets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsSecretsRequest() + + 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_user_workloads_secret_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + client.update_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + client.delete_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsSecretRequest() + + 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_user_workloads_config_map_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + client.create_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + client.get_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_maps_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + client.list_user_workloads_config_maps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsConfigMapsRequest() + + 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_user_workloads_config_map_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + client.update_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + client.delete_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsConfigMapRequest() + + 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_save_snapshot_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + client.save_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.SaveSnapshotRequest() + + 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_load_snapshot_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + client.load_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.LoadSnapshotRequest() + + 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_database_failover_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + client.database_failover(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DatabaseFailoverRequest() + + 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_fetch_database_properties_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + client.fetch_database_properties(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.FetchDatabasePropertiesRequest() + + assert args[0] == request_msg + + +def test_environments_rest_lro_client(): + client = EnvironmentsClient( + 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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EnvironmentsGrpcTransport, + ) + +def test_environments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_environments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.orchestration.airflow.service_v1.services.environments.transports.EnvironmentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_environment', + 'get_environment', + 'list_environments', + 'update_environment', + 'delete_environment', + 'execute_airflow_command', + 'stop_airflow_command', + 'poll_airflow_command', + 'list_workloads', + 'check_upgrade', + 'create_user_workloads_secret', + 'get_user_workloads_secret', + 'list_user_workloads_secrets', + 'update_user_workloads_secret', + 'delete_user_workloads_secret', + 'create_user_workloads_config_map', + 'get_user_workloads_config_map', + 'list_user_workloads_config_maps', + 'update_user_workloads_config_map', + 'delete_user_workloads_config_map', + 'save_snapshot', + 'load_snapshot', + 'database_failover', + 'fetch_database_properties', + 'get_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_environments_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.orchestration.airflow.service_v1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + 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_environments_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.orchestration.airflow.service_v1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport() + adc.assert_called_once() + + +def test_environments_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) + EnvironmentsClient() + 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.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +def test_environments_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.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + transports.EnvironmentsRestTransport, + ], +) +def test_environments_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.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_environments_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( + "composer.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="composer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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_environments_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.EnvironmentsRestTransport ( + 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_environments_host_no_port(transport_name): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://composer.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_environments_host_with_port(transport_name): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'composer.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://composer.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_environments_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EnvironmentsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EnvironmentsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_environment._session + session2 = client2.transport.create_environment._session + assert session1 != session2 + session1 = client1.transport.get_environment._session + session2 = client2.transport.get_environment._session + assert session1 != session2 + session1 = client1.transport.list_environments._session + session2 = client2.transport.list_environments._session + assert session1 != session2 + session1 = client1.transport.update_environment._session + session2 = client2.transport.update_environment._session + assert session1 != session2 + session1 = client1.transport.delete_environment._session + session2 = client2.transport.delete_environment._session + assert session1 != session2 + session1 = client1.transport.execute_airflow_command._session + session2 = client2.transport.execute_airflow_command._session + assert session1 != session2 + session1 = client1.transport.stop_airflow_command._session + session2 = client2.transport.stop_airflow_command._session + assert session1 != session2 + session1 = client1.transport.poll_airflow_command._session + session2 = client2.transport.poll_airflow_command._session + assert session1 != session2 + session1 = client1.transport.list_workloads._session + session2 = client2.transport.list_workloads._session + assert session1 != session2 + session1 = client1.transport.check_upgrade._session + session2 = client2.transport.check_upgrade._session + assert session1 != session2 + session1 = client1.transport.create_user_workloads_secret._session + session2 = client2.transport.create_user_workloads_secret._session + assert session1 != session2 + session1 = client1.transport.get_user_workloads_secret._session + session2 = client2.transport.get_user_workloads_secret._session + assert session1 != session2 + session1 = client1.transport.list_user_workloads_secrets._session + session2 = client2.transport.list_user_workloads_secrets._session + assert session1 != session2 + session1 = client1.transport.update_user_workloads_secret._session + session2 = client2.transport.update_user_workloads_secret._session + assert session1 != session2 + session1 = client1.transport.delete_user_workloads_secret._session + session2 = client2.transport.delete_user_workloads_secret._session + assert session1 != session2 + session1 = client1.transport.create_user_workloads_config_map._session + session2 = client2.transport.create_user_workloads_config_map._session + assert session1 != session2 + session1 = client1.transport.get_user_workloads_config_map._session + session2 = client2.transport.get_user_workloads_config_map._session + assert session1 != session2 + session1 = client1.transport.list_user_workloads_config_maps._session + session2 = client2.transport.list_user_workloads_config_maps._session + assert session1 != session2 + session1 = client1.transport.update_user_workloads_config_map._session + session2 = client2.transport.update_user_workloads_config_map._session + assert session1 != session2 + session1 = client1.transport.delete_user_workloads_config_map._session + session2 = client2.transport.delete_user_workloads_config_map._session + assert session1 != session2 + session1 = client1.transport.save_snapshot._session + session2 = client2.transport.save_snapshot._session + assert session1 != session2 + session1 = client1.transport.load_snapshot._session + session2 = client2.transport.load_snapshot._session + assert session1 != session2 + session1 = client1.transport.database_failover._session + session2 = client2.transport.database_failover._session + assert session1 != session2 + session1 = client1.transport.fetch_database_properties._session + session2 = client2.transport.fetch_database_properties._session + assert session1 != session2 +def test_environments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EnvironmentsGrpcTransport( + 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_environments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EnvironmentsGrpcAsyncIOTransport( + 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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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_environments_grpc_lro_client(): + client = EnvironmentsClient( + 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_environments_grpc_lro_async_client(): + client = EnvironmentsAsyncClient( + 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_environment_path(): + project = "squid" + location = "clam" + environment = "whelk" + expected = "projects/{project}/locations/{location}/environments/{environment}".format(project=project, location=location, environment=environment, ) + actual = EnvironmentsClient.environment_path(project, location, environment) + assert expected == actual + + +def test_parse_environment_path(): + expected = { + "project": "octopus", + "location": "oyster", + "environment": "nudibranch", + } + path = EnvironmentsClient.environment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_environment_path(path) + assert expected == actual + +def test_user_workloads_config_map_path(): + project = "cuttlefish" + location = "mussel" + environment = "winkle" + user_workloads_config_map = "nautilus" + expected = "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsConfigMaps/{user_workloads_config_map}".format(project=project, location=location, environment=environment, user_workloads_config_map=user_workloads_config_map, ) + actual = EnvironmentsClient.user_workloads_config_map_path(project, location, environment, user_workloads_config_map) + assert expected == actual + + +def test_parse_user_workloads_config_map_path(): + expected = { + "project": "scallop", + "location": "abalone", + "environment": "squid", + "user_workloads_config_map": "clam", + } + path = EnvironmentsClient.user_workloads_config_map_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_user_workloads_config_map_path(path) + assert expected == actual + +def test_user_workloads_secret_path(): + project = "whelk" + location = "octopus" + environment = "oyster" + user_workloads_secret = "nudibranch" + expected = "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsSecrets/{user_workloads_secret}".format(project=project, location=location, environment=environment, user_workloads_secret=user_workloads_secret, ) + actual = EnvironmentsClient.user_workloads_secret_path(project, location, environment, user_workloads_secret) + assert expected == actual + + +def test_parse_user_workloads_secret_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "environment": "winkle", + "user_workloads_secret": "nautilus", + } + path = EnvironmentsClient.user_workloads_secret_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_user_workloads_secret_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EnvironmentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = EnvironmentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = EnvironmentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = EnvironmentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = EnvironmentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.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 = EnvironmentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = EnvironmentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.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.EnvironmentsTransport, '_prep_wrapped_messages') as prep: + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EnvironmentsTransport, '_prep_wrapped_messages') as prep: + transport_class = EnvironmentsClient.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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport), +]) +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-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py new file mode 100644 index 000000000000..e9bfcea08472 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py @@ -0,0 +1,2847 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +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.orchestration.airflow.service_v1.services.image_versions import ImageVersionsAsyncClient +from google.cloud.orchestration.airflow.service_v1.services.image_versions import ImageVersionsClient +from google.cloud.orchestration.airflow.service_v1.services.image_versions import pagers +from google.cloud.orchestration.airflow.service_v1.services.image_versions import transports +from google.cloud.orchestration.airflow.service_v1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +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 ImageVersionsClient._get_default_mtls_endpoint(None) is None + assert ImageVersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ImageVersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ImageVersionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ImageVersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ImageVersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ImageVersionsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ImageVersionsClient._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 ImageVersionsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ImageVersionsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ImageVersionsClient._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 ImageVersionsClient._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 ImageVersionsClient._get_client_cert_source(None, False) is None + assert ImageVersionsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ImageVersionsClient._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 ImageVersionsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ImageVersionsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ImageVersionsClient._DEFAULT_UNIVERSE + default_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ImageVersionsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ImageVersionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "always") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + assert ImageVersionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + assert ImageVersionsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ImageVersionsClient._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 ImageVersionsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ImageVersionsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ImageVersionsClient._get_universe_domain(None, None) == ImageVersionsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ImageVersionsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = ImageVersionsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = ImageVersionsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageVersionsClient, "grpc"), + (ImageVersionsAsyncClient, "grpc_asyncio"), + (ImageVersionsClient, "rest"), +]) +def test_image_versions_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 == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://composer.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ImageVersionsGrpcTransport, "grpc"), + (transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ImageVersionsRestTransport, "rest"), +]) +def test_image_versions_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", [ + (ImageVersionsClient, "grpc"), + (ImageVersionsAsyncClient, "grpc_asyncio"), + (ImageVersionsClient, "rest"), +]) +def test_image_versions_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 == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://composer.googleapis.com' + ) + + +def test_image_versions_client_get_transport_class(): + transport = ImageVersionsClient.get_transport_class() + available_transports = [ + transports.ImageVersionsGrpcTransport, + transports.ImageVersionsRestTransport, + ] + assert transport in available_transports + + transport = ImageVersionsClient.get_transport_class("grpc") + assert transport == transports.ImageVersionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), +]) +@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) +def test_image_versions_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(ImageVersionsClient, '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(ImageVersionsClient, '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", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", "true"), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", "false"), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", "true"), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", "false"), +]) +@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_image_versions_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", [ + ImageVersionsClient, ImageVersionsAsyncClient +]) +@mock.patch.object(ImageVersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageVersionsAsyncClient)) +def test_image_versions_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", [ + ImageVersionsClient, ImageVersionsAsyncClient +]) +@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) +def test_image_versions_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ImageVersionsClient._DEFAULT_UNIVERSE + default_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ImageVersionsClient._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", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), +]) +def test_image_versions_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", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", grpc_helpers), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", None), +]) +def test_image_versions_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_image_versions_client_client_options_from_dict(): + with mock.patch('google.cloud.orchestration.airflow.service_v1.services.image_versions.transports.ImageVersionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ImageVersionsClient( + 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", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", grpc_helpers), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_image_versions_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( + "composer.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="composer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + image_versions.ListImageVersionsRequest, + dict, +]) +def test_list_image_versions(request_type, transport: str = 'grpc'): + client = ImageVersionsClient( + 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_image_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = image_versions.ListImageVersionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = image_versions.ListImageVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImageVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_image_versions_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 = ImageVersionsClient( + 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 = image_versions.ListImageVersionsRequest( + 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_image_versions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_image_versions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == image_versions.ListImageVersionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_image_versions_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 = ImageVersionsClient( + 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_image_versions 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_image_versions] = mock_rpc + request = {} + client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_image_versions(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_image_versions_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 = ImageVersionsAsyncClient( + 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_image_versions 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_image_versions] = mock_rpc + + request = {} + await client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_image_versions(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_image_versions_async(transport: str = 'grpc_asyncio', request_type=image_versions.ListImageVersionsRequest): + client = ImageVersionsAsyncClient( + 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_image_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = image_versions.ListImageVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImageVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_image_versions_async_from_dict(): + await test_list_image_versions_async(request_type=dict) + +def test_list_image_versions_field_headers(): + client = ImageVersionsClient( + 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 = image_versions.ListImageVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + call.return_value = image_versions.ListImageVersionsResponse() + client.list_image_versions(request) + + # Establish that the 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_image_versions_field_headers_async(): + client = ImageVersionsAsyncClient( + 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 = image_versions.ListImageVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse()) + await client.list_image_versions(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_image_versions_flattened(): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = image_versions.ListImageVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_image_versions( + 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_image_versions_flattened_error(): + client = ImageVersionsClient( + 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_image_versions( + image_versions.ListImageVersionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_image_versions_flattened_async(): + client = ImageVersionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = image_versions.ListImageVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_image_versions( + 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_image_versions_flattened_error_async(): + client = ImageVersionsAsyncClient( + 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_image_versions( + image_versions.ListImageVersionsRequest(), + parent='parent_value', + ) + + +def test_list_image_versions_pager(transport_name: str = "grpc"): + client = ImageVersionsClient( + 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_image_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + next_page_token='abc', + ), + image_versions.ListImageVersionsResponse( + image_versions=[], + next_page_token='def', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + ], + next_page_token='ghi', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_image_versions(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, image_versions.ImageVersion) + for i in results) +def test_list_image_versions_pages(transport_name: str = "grpc"): + client = ImageVersionsClient( + 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_image_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + next_page_token='abc', + ), + image_versions.ListImageVersionsResponse( + image_versions=[], + next_page_token='def', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + ], + next_page_token='ghi', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_image_versions(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_image_versions_async_pager(): + client = ImageVersionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + next_page_token='abc', + ), + image_versions.ListImageVersionsResponse( + image_versions=[], + next_page_token='def', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + ], + next_page_token='ghi', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_image_versions(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, image_versions.ImageVersion) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_image_versions_async_pages(): + client = ImageVersionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + next_page_token='abc', + ), + image_versions.ListImageVersionsResponse( + image_versions=[], + next_page_token='def', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + ], + next_page_token='ghi', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + ), + 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_image_versions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_image_versions_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 = ImageVersionsClient( + 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_image_versions 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_image_versions] = mock_rpc + + request = {} + client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_image_versions(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_image_versions_rest_flattened(): + client = ImageVersionsClient( + 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 = image_versions.ListImageVersionsResponse() + + # 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 = image_versions.ListImageVersionsResponse.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_image_versions(**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/*}/imageVersions" % client.transport._host, args[1]) + + +def test_list_image_versions_rest_flattened_error(transport: str = 'rest'): + client = ImageVersionsClient( + 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_image_versions( + image_versions.ListImageVersionsRequest(), + parent='parent_value', + ) + + +def test_list_image_versions_rest_pager(transport: str = 'rest'): + client = ImageVersionsClient( + 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 = ( + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + next_page_token='abc', + ), + image_versions.ListImageVersionsResponse( + image_versions=[], + next_page_token='def', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + ], + next_page_token='ghi', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(image_versions.ListImageVersionsResponse.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_image_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, image_versions.ImageVersion) + for i in results) + + pages = list(client.list_image_versions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageVersionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ImageVersionsClient( + 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 = ImageVersionsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageVersionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ImageVersionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ImageVersionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ImageVersionsGrpcTransport, + transports.ImageVersionsGrpcAsyncIOTransport, + transports.ImageVersionsRestTransport, +]) +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 = ImageVersionsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ImageVersionsClient( + 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_list_image_versions_empty_call_grpc(): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + call.return_value = image_versions.ListImageVersionsResponse() + client.list_image_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = image_versions.ListImageVersionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ImageVersionsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ImageVersionsAsyncClient( + 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_list_image_versions_empty_call_grpc_asyncio(): + client = ImageVersionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse( + next_page_token='next_page_token_value', + )) + await client.list_image_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = image_versions.ListImageVersionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ImageVersionsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_image_versions_rest_bad_request(request_type=image_versions.ListImageVersionsRequest): + client = ImageVersionsClient( + 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_image_versions(request) + + +@pytest.mark.parametrize("request_type", [ + image_versions.ListImageVersionsRequest, + dict, +]) +def test_list_image_versions_rest_call_success(request_type): + client = ImageVersionsClient( + 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 = image_versions.ListImageVersionsResponse( + 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 = image_versions.ListImageVersionsResponse.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_image_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImageVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_image_versions_rest_interceptors(null_interceptor): + transport = transports.ImageVersionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ImageVersionsRestInterceptor(), + ) + client = ImageVersionsClient(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.ImageVersionsRestInterceptor, "post_list_image_versions") as post, \ + mock.patch.object(transports.ImageVersionsRestInterceptor, "post_list_image_versions_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageVersionsRestInterceptor, "pre_list_image_versions") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = image_versions.ListImageVersionsRequest.pb(image_versions.ListImageVersionsRequest()) + 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 = image_versions.ListImageVersionsResponse.to_json(image_versions.ListImageVersionsResponse()) + req.return_value.content = return_value + + request = image_versions.ListImageVersionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = image_versions.ListImageVersionsResponse() + post_with_metadata.return_value = image_versions.ListImageVersionsResponse(), metadata + + client.list_image_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = ImageVersionsClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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_list_image_versions_empty_call_rest(): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + client.list_image_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = image_versions.ListImageVersionsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ImageVersionsGrpcTransport, + ) + +def test_image_versions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ImageVersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_image_versions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.orchestration.airflow.service_v1.services.image_versions.transports.ImageVersionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ImageVersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_image_versions', + 'get_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_image_versions_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.orchestration.airflow.service_v1.services.image_versions.transports.ImageVersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageVersionsTransport( + 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_image_versions_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.orchestration.airflow.service_v1.services.image_versions.transports.ImageVersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageVersionsTransport() + adc.assert_called_once() + + +def test_image_versions_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) + ImageVersionsClient() + 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.ImageVersionsGrpcTransport, + transports.ImageVersionsGrpcAsyncIOTransport, + ], +) +def test_image_versions_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.ImageVersionsGrpcTransport, + transports.ImageVersionsGrpcAsyncIOTransport, + transports.ImageVersionsRestTransport, + ], +) +def test_image_versions_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.ImageVersionsGrpcTransport, grpc_helpers), + (transports.ImageVersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_image_versions_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( + "composer.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="composer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) +def test_image_versions_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_image_versions_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.ImageVersionsRestTransport ( + 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_image_versions_host_no_port(transport_name): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://composer.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_image_versions_host_with_port(transport_name): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'composer.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://composer.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_image_versions_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ImageVersionsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ImageVersionsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_image_versions._session + session2 = client2.transport.list_image_versions._session + assert session1 != session2 +def test_image_versions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ImageVersionsGrpcTransport( + 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_image_versions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ImageVersionsGrpcAsyncIOTransport( + 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.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) +def test_image_versions_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.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) +def test_image_versions_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_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ImageVersionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ImageVersionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ImageVersionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = ImageVersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ImageVersionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ImageVersionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ImageVersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ImageVersionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ImageVersionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = ImageVersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ImageVersionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ImageVersionsClient.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 = ImageVersionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ImageVersionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ImageVersionsClient.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.ImageVersionsTransport, '_prep_wrapped_messages') as prep: + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ImageVersionsTransport, '_prep_wrapped_messages') as prep: + transport_class = ImageVersionsClient.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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport), +]) +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-orchestration-airflow/v1beta1/.coveragerc b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.coveragerc new file mode 100644 index 000000000000..7b27e381927a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/orchestration/airflow/service/__init__.py + google/cloud/orchestration/airflow/service/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-orchestration-airflow/v1beta1/.flake8 b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/MANIFEST.in new file mode 100644 index 000000000000..20f737545f5e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/orchestration/airflow/service *.py +recursive-include google/cloud/orchestration/airflow/service_v1beta1 *.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/README.rst new file mode 100644 index 000000000000..4f24fd5ece7c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Cloud Orchestration Airflow Service 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 Orchestration Airflow Service 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 + + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + + +Examples +^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + + +Examples +^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/airflow-service-v1beta1-py.tar.gz b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/airflow-service-v1beta1-py.tar.gz new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py new file mode 100644 index 000000000000..b97cc0c9fd88 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow-service 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-orchestration-airflow-service" +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 Orchestration Airflow 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-orchestration-airflow-service-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-orchestration-airflow-service.tex", + u"google-cloud-orchestration-airflow-service 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-orchestration-airflow-service", + u"Google Cloud Orchestration Airflow Service 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-orchestration-airflow-service", + u"google-cloud-orchestration-airflow-service Documentation", + author, + "google-cloud-orchestration-airflow-service", + "GAPIC library for Google Cloud Orchestration Airflow Service 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-orchestration-airflow/v1beta1/docs/index.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/index.rst new file mode 100644 index 000000000000..99ae5d015386 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + service_v1beta1/services_ + service_v1beta1/types_ diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/environments.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/environments.rst new file mode 100644 index 000000000000..9a3d3abd2249 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/environments.rst @@ -0,0 +1,10 @@ +Environments +------------------------------ + +.. automodule:: google.cloud.orchestration.airflow.service_v1beta1.services.environments + :members: + :inherited-members: + +.. automodule:: google.cloud.orchestration.airflow.service_v1beta1.services.environments.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/image_versions.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/image_versions.rst new file mode 100644 index 000000000000..b6b092000589 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/image_versions.rst @@ -0,0 +1,10 @@ +ImageVersions +------------------------------- + +.. automodule:: google.cloud.orchestration.airflow.service_v1beta1.services.image_versions + :members: + :inherited-members: + +.. automodule:: google.cloud.orchestration.airflow.service_v1beta1.services.image_versions.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/services_.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/services_.rst new file mode 100644 index 000000000000..028dbc969e68 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/services_.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Orchestration Airflow Service v1beta1 API +=================================================================== +.. toctree:: + :maxdepth: 2 + + environments + image_versions diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/types_.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/types_.rst new file mode 100644 index 000000000000..9caa2086107d --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Orchestration Airflow Service v1beta1 API +================================================================ + +.. automodule:: google.cloud.orchestration.airflow.service_v1beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py new file mode 100644 index 000000000000..663bb823e81a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.orchestration.airflow.service_v1beta1.services.environments.client import EnvironmentsClient +from google.cloud.orchestration.airflow.service_v1beta1.services.environments.async_client import EnvironmentsAsyncClient +from google.cloud.orchestration.airflow.service_v1beta1.services.image_versions.client import ImageVersionsClient +from google.cloud.orchestration.airflow.service_v1beta1.services.image_versions.async_client import ImageVersionsAsyncClient + +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import AirflowMetadataRetentionPolicyConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CheckUpgradeRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CheckUpgradeResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CloudDataLineageIntegration +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CreateEnvironmentRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CreateUserWorkloadsConfigMapRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CreateUserWorkloadsSecretRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DatabaseConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DatabaseFailoverRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DatabaseFailoverResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DataRetentionConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DeleteEnvironmentRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DeleteUserWorkloadsConfigMapRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DeleteUserWorkloadsSecretRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import EncryptionConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import Environment +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import EnvironmentConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ExecuteAirflowCommandRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ExecuteAirflowCommandResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import FetchDatabasePropertiesRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import FetchDatabasePropertiesResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import GetEnvironmentRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import GetUserWorkloadsConfigMapRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import GetUserWorkloadsSecretRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import IPAllocationPolicy +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListEnvironmentsRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListEnvironmentsResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListUserWorkloadsConfigMapsRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListUserWorkloadsConfigMapsResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListUserWorkloadsSecretsRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListUserWorkloadsSecretsResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListWorkloadsRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListWorkloadsResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import LoadSnapshotRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import LoadSnapshotResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import MaintenanceWindow +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import MasterAuthorizedNetworksConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import NetworkingConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import NodeConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import PollAirflowCommandRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import PollAirflowCommandResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import PrivateClusterConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import PrivateEnvironmentConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import RecoveryConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import RestartWebServerRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import SaveSnapshotRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import SaveSnapshotResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ScheduledSnapshotsConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import SoftwareConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import StopAirflowCommandRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import StopAirflowCommandResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import StorageConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import TaskLogsRetentionConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import UpdateEnvironmentRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import UpdateUserWorkloadsConfigMapRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import UpdateUserWorkloadsSecretRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import UserWorkloadsConfigMap +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import UserWorkloadsSecret +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import WebServerConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import WebServerNetworkAccessControl +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import WorkloadsConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.image_versions import ImageVersion +from google.cloud.orchestration.airflow.service_v1beta1.types.image_versions import ListImageVersionsRequest +from google.cloud.orchestration.airflow.service_v1beta1.types.image_versions import ListImageVersionsResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.operations import OperationMetadata + +__all__ = ('EnvironmentsClient', + 'EnvironmentsAsyncClient', + 'ImageVersionsClient', + 'ImageVersionsAsyncClient', + 'AirflowMetadataRetentionPolicyConfig', + 'CheckUpgradeRequest', + 'CheckUpgradeResponse', + 'CloudDataLineageIntegration', + 'CreateEnvironmentRequest', + 'CreateUserWorkloadsConfigMapRequest', + 'CreateUserWorkloadsSecretRequest', + 'DatabaseConfig', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'DataRetentionConfig', + 'DeleteEnvironmentRequest', + 'DeleteUserWorkloadsConfigMapRequest', + 'DeleteUserWorkloadsSecretRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'GetEnvironmentRequest', + 'GetUserWorkloadsConfigMapRequest', + 'GetUserWorkloadsSecretRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'ListUserWorkloadsConfigMapsRequest', + 'ListUserWorkloadsConfigMapsResponse', + 'ListUserWorkloadsSecretsRequest', + 'ListUserWorkloadsSecretsResponse', + 'ListWorkloadsRequest', + 'ListWorkloadsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'RestartWebServerRequest', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'StorageConfig', + 'TaskLogsRetentionConfig', + 'UpdateEnvironmentRequest', + 'UpdateUserWorkloadsConfigMapRequest', + 'UpdateUserWorkloadsSecretRequest', + 'UserWorkloadsConfigMap', + 'UserWorkloadsSecret', + 'WebServerConfig', + 'WebServerNetworkAccessControl', + 'WorkloadsConfig', + 'ImageVersion', + 'ListImageVersionsRequest', + 'ListImageVersionsResponse', + 'OperationMetadata', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/gapic_version.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/py.typed b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/py.typed new file mode 100644 index 000000000000..a957d7b8dbec --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-orchestration-airflow-service package uses inline types. diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py new file mode 100644 index 000000000000..7b79b2ddb43b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.image_versions import ImageVersionsClient +from .services.image_versions import ImageVersionsAsyncClient + +from .types.environments import AirflowMetadataRetentionPolicyConfig +from .types.environments import CheckUpgradeRequest +from .types.environments import CheckUpgradeResponse +from .types.environments import CloudDataLineageIntegration +from .types.environments import CreateEnvironmentRequest +from .types.environments import CreateUserWorkloadsConfigMapRequest +from .types.environments import CreateUserWorkloadsSecretRequest +from .types.environments import DatabaseConfig +from .types.environments import DatabaseFailoverRequest +from .types.environments import DatabaseFailoverResponse +from .types.environments import DataRetentionConfig +from .types.environments import DeleteEnvironmentRequest +from .types.environments import DeleteUserWorkloadsConfigMapRequest +from .types.environments import DeleteUserWorkloadsSecretRequest +from .types.environments import EncryptionConfig +from .types.environments import Environment +from .types.environments import EnvironmentConfig +from .types.environments import ExecuteAirflowCommandRequest +from .types.environments import ExecuteAirflowCommandResponse +from .types.environments import FetchDatabasePropertiesRequest +from .types.environments import FetchDatabasePropertiesResponse +from .types.environments import GetEnvironmentRequest +from .types.environments import GetUserWorkloadsConfigMapRequest +from .types.environments import GetUserWorkloadsSecretRequest +from .types.environments import IPAllocationPolicy +from .types.environments import ListEnvironmentsRequest +from .types.environments import ListEnvironmentsResponse +from .types.environments import ListUserWorkloadsConfigMapsRequest +from .types.environments import ListUserWorkloadsConfigMapsResponse +from .types.environments import ListUserWorkloadsSecretsRequest +from .types.environments import ListUserWorkloadsSecretsResponse +from .types.environments import ListWorkloadsRequest +from .types.environments import ListWorkloadsResponse +from .types.environments import LoadSnapshotRequest +from .types.environments import LoadSnapshotResponse +from .types.environments import MaintenanceWindow +from .types.environments import MasterAuthorizedNetworksConfig +from .types.environments import NetworkingConfig +from .types.environments import NodeConfig +from .types.environments import PollAirflowCommandRequest +from .types.environments import PollAirflowCommandResponse +from .types.environments import PrivateClusterConfig +from .types.environments import PrivateEnvironmentConfig +from .types.environments import RecoveryConfig +from .types.environments import RestartWebServerRequest +from .types.environments import SaveSnapshotRequest +from .types.environments import SaveSnapshotResponse +from .types.environments import ScheduledSnapshotsConfig +from .types.environments import SoftwareConfig +from .types.environments import StopAirflowCommandRequest +from .types.environments import StopAirflowCommandResponse +from .types.environments import StorageConfig +from .types.environments import TaskLogsRetentionConfig +from .types.environments import UpdateEnvironmentRequest +from .types.environments import UpdateUserWorkloadsConfigMapRequest +from .types.environments import UpdateUserWorkloadsSecretRequest +from .types.environments import UserWorkloadsConfigMap +from .types.environments import UserWorkloadsSecret +from .types.environments import WebServerConfig +from .types.environments import WebServerNetworkAccessControl +from .types.environments import WorkloadsConfig +from .types.image_versions import ImageVersion +from .types.image_versions import ListImageVersionsRequest +from .types.image_versions import ListImageVersionsResponse +from .types.operations import OperationMetadata + +__all__ = ( + 'EnvironmentsAsyncClient', + 'ImageVersionsAsyncClient', +'AirflowMetadataRetentionPolicyConfig', +'CheckUpgradeRequest', +'CheckUpgradeResponse', +'CloudDataLineageIntegration', +'CreateEnvironmentRequest', +'CreateUserWorkloadsConfigMapRequest', +'CreateUserWorkloadsSecretRequest', +'DataRetentionConfig', +'DatabaseConfig', +'DatabaseFailoverRequest', +'DatabaseFailoverResponse', +'DeleteEnvironmentRequest', +'DeleteUserWorkloadsConfigMapRequest', +'DeleteUserWorkloadsSecretRequest', +'EncryptionConfig', +'Environment', +'EnvironmentConfig', +'EnvironmentsClient', +'ExecuteAirflowCommandRequest', +'ExecuteAirflowCommandResponse', +'FetchDatabasePropertiesRequest', +'FetchDatabasePropertiesResponse', +'GetEnvironmentRequest', +'GetUserWorkloadsConfigMapRequest', +'GetUserWorkloadsSecretRequest', +'IPAllocationPolicy', +'ImageVersion', +'ImageVersionsClient', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListImageVersionsRequest', +'ListImageVersionsResponse', +'ListUserWorkloadsConfigMapsRequest', +'ListUserWorkloadsConfigMapsResponse', +'ListUserWorkloadsSecretsRequest', +'ListUserWorkloadsSecretsResponse', +'ListWorkloadsRequest', +'ListWorkloadsResponse', +'LoadSnapshotRequest', +'LoadSnapshotResponse', +'MaintenanceWindow', +'MasterAuthorizedNetworksConfig', +'NetworkingConfig', +'NodeConfig', +'OperationMetadata', +'PollAirflowCommandRequest', +'PollAirflowCommandResponse', +'PrivateClusterConfig', +'PrivateEnvironmentConfig', +'RecoveryConfig', +'RestartWebServerRequest', +'SaveSnapshotRequest', +'SaveSnapshotResponse', +'ScheduledSnapshotsConfig', +'SoftwareConfig', +'StopAirflowCommandRequest', +'StopAirflowCommandResponse', +'StorageConfig', +'TaskLogsRetentionConfig', +'UpdateEnvironmentRequest', +'UpdateUserWorkloadsConfigMapRequest', +'UpdateUserWorkloadsSecretRequest', +'UserWorkloadsConfigMap', +'UserWorkloadsSecret', +'WebServerConfig', +'WebServerNetworkAccessControl', +'WorkloadsConfig', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json new file mode 100644 index 000000000000..f3393a50e431 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json @@ -0,0 +1,437 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.orchestration.airflow.service_v1beta1", + "protoPackage": "google.cloud.orchestration.airflow.service.v1beta1", + "schema": "1.0", + "services": { + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CheckUpgrade": { + "methods": [ + "check_upgrade" + ] + }, + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "CreateUserWorkloadsConfigMap": { + "methods": [ + "create_user_workloads_config_map" + ] + }, + "CreateUserWorkloadsSecret": { + "methods": [ + "create_user_workloads_secret" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "DeleteUserWorkloadsConfigMap": { + "methods": [ + "delete_user_workloads_config_map" + ] + }, + "DeleteUserWorkloadsSecret": { + "methods": [ + "delete_user_workloads_secret" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetUserWorkloadsConfigMap": { + "methods": [ + "get_user_workloads_config_map" + ] + }, + "GetUserWorkloadsSecret": { + "methods": [ + "get_user_workloads_secret" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "ListUserWorkloadsConfigMaps": { + "methods": [ + "list_user_workloads_config_maps" + ] + }, + "ListUserWorkloadsSecrets": { + "methods": [ + "list_user_workloads_secrets" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "RestartWebServer": { + "methods": [ + "restart_web_server" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + }, + "UpdateUserWorkloadsConfigMap": { + "methods": [ + "update_user_workloads_config_map" + ] + }, + "UpdateUserWorkloadsSecret": { + "methods": [ + "update_user_workloads_secret" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CheckUpgrade": { + "methods": [ + "check_upgrade" + ] + }, + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "CreateUserWorkloadsConfigMap": { + "methods": [ + "create_user_workloads_config_map" + ] + }, + "CreateUserWorkloadsSecret": { + "methods": [ + "create_user_workloads_secret" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "DeleteUserWorkloadsConfigMap": { + "methods": [ + "delete_user_workloads_config_map" + ] + }, + "DeleteUserWorkloadsSecret": { + "methods": [ + "delete_user_workloads_secret" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetUserWorkloadsConfigMap": { + "methods": [ + "get_user_workloads_config_map" + ] + }, + "GetUserWorkloadsSecret": { + "methods": [ + "get_user_workloads_secret" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "ListUserWorkloadsConfigMaps": { + "methods": [ + "list_user_workloads_config_maps" + ] + }, + "ListUserWorkloadsSecrets": { + "methods": [ + "list_user_workloads_secrets" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "RestartWebServer": { + "methods": [ + "restart_web_server" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + }, + "UpdateUserWorkloadsConfigMap": { + "methods": [ + "update_user_workloads_config_map" + ] + }, + "UpdateUserWorkloadsSecret": { + "methods": [ + "update_user_workloads_secret" + ] + } + } + }, + "rest": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CheckUpgrade": { + "methods": [ + "check_upgrade" + ] + }, + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "CreateUserWorkloadsConfigMap": { + "methods": [ + "create_user_workloads_config_map" + ] + }, + "CreateUserWorkloadsSecret": { + "methods": [ + "create_user_workloads_secret" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "DeleteUserWorkloadsConfigMap": { + "methods": [ + "delete_user_workloads_config_map" + ] + }, + "DeleteUserWorkloadsSecret": { + "methods": [ + "delete_user_workloads_secret" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetUserWorkloadsConfigMap": { + "methods": [ + "get_user_workloads_config_map" + ] + }, + "GetUserWorkloadsSecret": { + "methods": [ + "get_user_workloads_secret" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "ListUserWorkloadsConfigMaps": { + "methods": [ + "list_user_workloads_config_maps" + ] + }, + "ListUserWorkloadsSecrets": { + "methods": [ + "list_user_workloads_secrets" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "RestartWebServer": { + "methods": [ + "restart_web_server" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + }, + "UpdateUserWorkloadsConfigMap": { + "methods": [ + "update_user_workloads_config_map" + ] + }, + "UpdateUserWorkloadsSecret": { + "methods": [ + "update_user_workloads_secret" + ] + } + } + } + } + }, + "ImageVersions": { + "clients": { + "grpc": { + "libraryClient": "ImageVersionsClient", + "rpcs": { + "ListImageVersions": { + "methods": [ + "list_image_versions" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ImageVersionsAsyncClient", + "rpcs": { + "ListImageVersions": { + "methods": [ + "list_image_versions" + ] + } + } + }, + "rest": { + "libraryClient": "ImageVersionsClient", + "rpcs": { + "ListImageVersions": { + "methods": [ + "list_image_versions" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/py.typed b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/py.typed new file mode 100644 index 000000000000..a957d7b8dbec --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-orchestration-airflow-service package uses inline types. diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/__init__.py new file mode 100644 index 000000000000..8aea3f820923 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/__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 EnvironmentsClient +from .async_client import EnvironmentsAsyncClient + +__all__ = ( + 'EnvironmentsClient', + 'EnvironmentsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py new file mode 100644 index 000000000000..0a9a29c0f361 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py @@ -0,0 +1,3350 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_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.orchestration.airflow.service_v1beta1.services.environments import pagers +from google.cloud.orchestration.airflow.service_v1beta1.types import environments +from google.cloud.orchestration.airflow.service_v1beta1.types import operations +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 EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .client import EnvironmentsClient + +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 EnvironmentsAsyncClient: + """Managed Apache Airflow Environments.""" + + _client: EnvironmentsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = EnvironmentsClient._DEFAULT_UNIVERSE + + environment_path = staticmethod(EnvironmentsClient.environment_path) + parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) + user_workloads_config_map_path = staticmethod(EnvironmentsClient.user_workloads_config_map_path) + parse_user_workloads_config_map_path = staticmethod(EnvironmentsClient.parse_user_workloads_config_map_path) + user_workloads_secret_path = staticmethod(EnvironmentsClient.user_workloads_secret_path) + parse_user_workloads_secret_path = staticmethod(EnvironmentsClient.parse_user_workloads_secret_path) + common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) + parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) + common_project_path = staticmethod(EnvironmentsClient.common_project_path) + parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) + common_location_path = staticmethod(EnvironmentsClient.common_location_path) + parse_common_location_path = staticmethod(EnvironmentsClient.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: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, 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: + EnvironmentsAsyncClient: The constructed client. + """ + return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, 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 EnvironmentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EnvironmentsTransport: + """Returns the transport used by the client instance. + + Returns: + EnvironmentsTransport: 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 = EnvironmentsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EnvironmentsTransport, Callable[..., EnvironmentsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the environments 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,EnvironmentsTransport,Callable[..., EnvironmentsTransport]]]): + 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 EnvironmentsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EnvironmentsClient( + 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.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient`.", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "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.orchestration.airflow.service.v1beta1.Environments", + "credentialsType": None, + } + ) + + async def create_environment(self, + request: Optional[Union[environments.CreateEnvironmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + environment: Optional[environments.Environment] = 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"""Create a new environment. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_create_environment(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateEnvironmentRequest( + ) + + # Make the request + operation = client.create_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateEnvironmentRequest, dict]]): + The request object. Create a new environment. + parent (:class:`str`): + The parent must be of the form + "projects/{projectId}/locations/{locationId}". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.Environment`): + The environment to create. + This corresponds to the ``environment`` 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.orchestration.airflow.service_v1beta1.types.Environment` + An environment for running orchestration tasks. + + """ + # 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. + flattened_params = [parent, environment] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateEnvironmentRequest): + request = environments.CreateEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if environment is not None: + request.environment = environment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_environment] + + # 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, + environments.Environment, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_environment(self, + request: Optional[Union[environments.GetEnvironmentRequest, 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]]] = (), + ) -> environments.Environment: + r"""Get an existing environment. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_get_environment(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.GetEnvironmentRequest( + ) + + # Make the request + response = await client.get_environment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest, dict]]): + The request object. Get an environment. + name (:class:`str`): + The resource name of the environment + to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1beta1.types.Environment: + An environment for running + orchestration tasks. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetEnvironmentRequest): + request = environments.GetEnvironmentRequest(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_environment] + + # 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_environments(self, + request: Optional[Union[environments.ListEnvironmentsRequest, 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.ListEnvironmentsAsyncPager: + r"""List environments. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_list_environments(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ListEnvironmentsRequest( + ) + + # Make the request + page_result = client.list_environments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest, dict]]): + The request object. List environments in a project and + location. + parent (:class:`str`): + List environments in the given + project and location, in the form: + "projects/{projectId}/locations/{locationId}" + + 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsAsyncPager: + The environments in a project and + location. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListEnvironmentsRequest): + request = environments.ListEnvironmentsRequest(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_environments] + + # 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.ListEnvironmentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_environment(self, + request: Optional[Union[environments.UpdateEnvironmentRequest, dict]] = None, + *, + name: Optional[str] = None, + environment: Optional[environments.Environment] = 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"""Update an environment. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_update_environment(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateEnvironmentRequest( + ) + + # Make the request + operation = client.update_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateEnvironmentRequest, dict]]): + The request object. Update an environment. + name (:class:`str`): + The relative resource name of the + environment to update, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.Environment`): + A patch environment. Fields specified by the + ``updateMask`` will be copied from the patch environment + into the environment under update. + + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. A comma-separated list of paths, relative to + ``Environment``, of fields to update. For example, to + set the version of scikit-learn to install in the + environment to 0.19.0 and to remove an existing + installation of argparse, the ``updateMask`` parameter + would include the following two ``paths`` values: + "config.softwareConfig.pypiPackages.scikit-learn" and + "config.softwareConfig.pypiPackages.argparse". The + included patch environment would specify the + scikit-learn version as follows: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "scikit-learn":"==0.19.0" + } + } + } + } + + Note that in the above example, any existing PyPI + packages other than scikit-learn and argparse will be + unaffected. + + Only one update type may be included in a single + request's ``updateMask``. For example, one cannot update + both the PyPI packages and labels in the same request. + However, it is possible to update multiple members of a + map field simultaneously in the same request. For + example, to set the labels "label1" and "label2" while + clearing "label3" (assuming it already exists), one can + provide the paths "labels.label1", "labels.label2", and + "labels.label3" and populate the patch environment as + follows: + + :: + + { + "labels":{ + "label1":"new-label1-value" + "label2":"new-label2-value" + } + } + + Note that in the above example, any existing labels that + are not included in the ``updateMask`` will be + unaffected. + + It is also possible to replace an entire map field by + providing the map field's path in the ``updateMask``. + The new value of the field will be that which is + provided in the patch environment. For example, to + delete all pre-existing user-specified PyPI packages and + install botocore at version 1.7.14, the ``updateMask`` + would contain the path + "config.softwareConfig.pypiPackages", and the patch + environment would be the following: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "botocore":"==1.7.14" + } + } + } + } + + **Note:** Only the following fields can be updated: + + - ``config.softwareConfig.pypiPackages`` + + - Replace all custom custom PyPI packages. If a + replacement package map is not included in + ``environment``, all custom PyPI packages are + cleared. It is an error to provide both this mask + and a mask specifying an individual package. + + - ``config.softwareConfig.pypiPackages.``\ packagename + + - Update the custom PyPI package *packagename*, + preserving other packages. To delete the package, + include it in ``updateMask``, and omit the mapping + for it in + ``environment.config.softwareConfig.pypiPackages``. + It is an error to provide both a mask of this form + and the ``config.softwareConfig.pypiPackages`` + mask. + + - ``labels`` + + - Replace all environment labels. If a replacement + labels map is not included in ``environment``, all + labels are cleared. It is an error to provide both + this mask and a mask specifying one or more + individual labels. + + - ``labels.``\ labelName + + - Set the label named *labelName*, while preserving + other labels. To delete the label, include it in + ``updateMask`` and omit its mapping in + ``environment.labels``. It is an error to provide + both a mask of this form and the ``labels`` mask. + + - ``config.nodeCount`` + + - Horizontally scale the number of nodes in the + environment. An integer greater than or equal to 3 + must be provided in the ``config.nodeCount`` + field. Supported for Cloud Composer environments + in versions composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerNetworkAccessControl`` + + - Replace the environment's current + WebServerNetworkAccessControl. + + - ``config.softwareConfig.airflowConfigOverrides`` + + - Replace all Apache Airflow config overrides. If a + replacement config overrides map is not included + in ``environment``, all config overrides are + cleared. It is an error to provide both this mask + and a mask specifying one or more individual + config overrides. + + - ``config.softwareConfig.airflowConfigOverrides.``\ section-name + + - Override the Apache Airflow config property *name* + in the section named *section*, preserving other + properties. To delete the property override, + include it in ``updateMask`` and omit its mapping + in + ``environment.config.softwareConfig.airflowConfigOverrides``. + It is an error to provide both a mask of this form + and the + ``config.softwareConfig.airflowConfigOverrides`` + mask. + + - ``config.softwareConfig.envVariables`` + + - Replace all environment variables. If a + replacement environment variable map is not + included in ``environment``, all custom + environment variables are cleared. + + - ``config.softwareConfig.imageVersion`` + + - Upgrade the version of the environment in-place. + Refer to ``SoftwareConfig.image_version`` for + information on how to format the new image + version. Additionally, the new image version + cannot effect a version downgrade, and must match + the current image version's Composer and Airflow + major versions. Consult the `Cloud Composer + version + list `__ + for valid values. + + - ``config.softwareConfig.schedulerCount`` + + - Horizontally scale the number of schedulers in + Airflow. A positive integer not greater than the + number of nodes must be provided in the + ``config.softwareConfig.schedulerCount`` field. + Supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-2.*.*. + + - ``config.softwareConfig.cloudDataLineageIntegration`` + + - Configuration for Cloud Data Lineage integration. + + - ``config.databaseConfig.machineType`` + + - Cloud SQL machine type used by Airflow database. + It has to be one of: db-n1-standard-2, + db-n1-standard-4, db-n1-standard-8 or + db-n1-standard-16. Supported for Cloud Composer + environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerConfig.machineType`` + + - Machine type on which Airflow web server is + running. It has to be one of: + composer-n1-webserver-2, composer-n1-webserver-4 + or composer-n1-webserver-8. Supported for Cloud + Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.maintenanceWindow`` + + - Maintenance window during which Cloud Composer + components may be under maintenance. + + - ``config.workloadsConfig`` + + - The workloads configuration settings for the GKE + cluster associated with the Cloud Composer + environment. Supported for Cloud Composer + environments in versions + composer-2.\ *.*-airflow-*.*.\* and newer. + + - ``config.environmentSize`` + + - The size of the Cloud Composer environment. + Supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and + newer. + + 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.orchestration.airflow.service_v1beta1.types.Environment` + An environment for running orchestration tasks. + + """ + # 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. + flattened_params = [name, environment, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateEnvironmentRequest): + request = environments.UpdateEnvironmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if environment is not None: + request.environment = environment + 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_environment] + + # 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, + environments.Environment, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_environment(self, + request: Optional[Union[environments.DeleteEnvironmentRequest, 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"""Delete an environment. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_delete_environment(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteEnvironmentRequest( + ) + + # Make the request + operation = client.delete_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteEnvironmentRequest, dict]]): + The request object. Delete an environment. + name (:class:`str`): + The environment to delete, in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteEnvironmentRequest): + request = environments.DeleteEnvironmentRequest(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_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def restart_web_server(self, + request: Optional[Union[environments.RestartWebServerRequest, dict]] = 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"""Restart Airflow web server. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_restart_web_server(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.RestartWebServerRequest( + ) + + # Make the request + operation = client.restart_web_server(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest, dict]]): + The request object. Restart Airflow web server. + 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.orchestration.airflow.service_v1beta1.types.Environment` + An environment for running orchestration tasks. + + """ + # 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, environments.RestartWebServerRequest): + request = environments.RestartWebServerRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.restart_web_server] + + # 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, + environments.Environment, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def check_upgrade(self, + request: Optional[Union[environments.CheckUpgradeRequest, dict]] = 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"""Check if an upgrade operation on the environment will + succeed. + In case of problems detailed info can be found in the + returned 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.orchestration.airflow import service_v1beta1 + + async def sample_check_upgrade(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.CheckUpgradeRequest( + ) + + # Make the request + operation = client.check_upgrade(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeRequest, dict]]): + The request object. Request to check whether image + upgrade will succeed. + 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.orchestration.airflow.service_v1beta1.types.CheckUpgradeResponse` Message containing information about the result of an upgrade check + operation. + + """ + # 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, environments.CheckUpgradeRequest): + request = environments.CheckUpgradeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.check_upgrade] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.CheckUpgradeResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def execute_airflow_command(self, + request: Optional[Union[environments.ExecuteAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.ExecuteAirflowCommandResponse: + r"""Executes Airflow CLI command. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_execute_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ExecuteAirflowCommandRequest( + ) + + # Make the request + response = await client.execute_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandRequest, dict]]): + The request object. Execute Airflow Command request. + 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.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandResponse: + Response to + ExecuteAirflowCommandRequest. + + """ + # 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, environments.ExecuteAirflowCommandRequest): + request = environments.ExecuteAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.execute_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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 stop_airflow_command(self, + request: Optional[Union[environments.StopAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.StopAirflowCommandResponse: + r"""Stops Airflow CLI command execution. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_stop_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.StopAirflowCommandRequest( + ) + + # Make the request + response = await client.stop_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest, dict]]): + The request object. Stop Airflow Command request. + 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.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse: + Response to + StopAirflowCommandRequest. + + """ + # 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, environments.StopAirflowCommandRequest): + request = environments.StopAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.stop_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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 poll_airflow_command(self, + request: Optional[Union[environments.PollAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.PollAirflowCommandResponse: + r"""Polls Airflow CLI command execution and fetches logs. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_poll_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.PollAirflowCommandRequest( + ) + + # Make the request + response = await client.poll_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest, dict]]): + The request object. Poll Airflow Command request. + 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.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse: + Response to + PollAirflowCommandRequest. + + """ + # 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, environments.PollAirflowCommandRequest): + request = environments.PollAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.poll_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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_workloads(self, + request: Optional[Union[environments.ListWorkloadsRequest, 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.ListWorkloadsAsyncPager: + r"""Lists workloads in a Cloud Composer environment. Workload is a + unit that runs a single Composer component. + + This method is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_list_workloads(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest, dict]]): + The request object. Request for listing workloads in a + Cloud Composer environment. + parent (:class:`str`): + Required. The environment name to get + workloads for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListWorkloadsAsyncPager: + Response to ListWorkloadsRequest. + + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListWorkloadsRequest): + request = environments.ListWorkloadsRequest(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_workloads] + + # 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.ListWorkloadsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_user_workloads_secret(self, + request: Optional[Union[environments.CreateUserWorkloadsSecretRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_create_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateUserWorkloadsSecretRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsSecretRequest, dict]]): + The request object. Create user workloads Secret request. + parent (:class:`str`): + Required. The environment name to + create a Secret for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_workloads_secret (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret`): + Required. User workloads Secret to + create. + + This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [parent, user_workloads_secret] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateUserWorkloadsSecretRequest): + request = environments.CreateUserWorkloadsSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_workloads_secret is not None: + request.user_workloads_secret = user_workloads_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_user_workloads_secret] + + # 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 get_user_workloads_secret(self, + request: Optional[Union[environments.GetUserWorkloadsSecretRequest, 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]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Gets an existing user workloads Secret. Values of the "data" + field in the response are cleared. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_get_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.GetUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsSecretRequest, dict]]): + The request object. Get user workloads Secret request. + name (:class:`str`): + Required. The resource name of the + Secret to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" + + 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetUserWorkloadsSecretRequest): + request = environments.GetUserWorkloadsSecretRequest(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_user_workloads_secret] + + # 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_user_workloads_secrets(self, + request: Optional[Union[environments.ListUserWorkloadsSecretsRequest, 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.ListUserWorkloadsSecretsAsyncPager: + r"""Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_list_user_workloads_secrets(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ListUserWorkloadsSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_secrets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest, dict]]): + The request object. List user workloads Secrets request. + parent (:class:`str`): + Required. List Secrets in the given + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsSecretsAsyncPager: + The user workloads Secrets for a + given environment. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListUserWorkloadsSecretsRequest): + request = environments.ListUserWorkloadsSecretsRequest(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_user_workloads_secrets] + + # 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.ListUserWorkloadsSecretsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_user_workloads_secret(self, + request: Optional[Union[environments.UpdateUserWorkloadsSecretRequest, dict]] = None, + *, + user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_update_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateUserWorkloadsSecretRequest( + ) + + # Make the request + response = await client.update_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsSecretRequest, dict]]): + The request object. Update user workloads Secret request. + user_workloads_secret (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret`): + Optional. User workloads Secret to + override. + + This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [user_workloads_secret] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateUserWorkloadsSecretRequest): + request = environments.UpdateUserWorkloadsSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_workloads_secret is not None: + request.user_workloads_secret = user_workloads_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_user_workloads_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user_workloads_secret.name", request.user_workloads_secret.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_user_workloads_secret(self, + request: Optional[Union[environments.DeleteUserWorkloadsSecretRequest, 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]]] = (), + ) -> None: + r"""Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_delete_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_workloads_secret(request=request) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsSecretRequest, dict]]): + The request object. Delete user workloads Secret request. + name (:class:`str`): + Required. The Secret to delete, in + the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" + + 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`. + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteUserWorkloadsSecretRequest): + request = environments.DeleteUserWorkloadsSecretRequest(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_user_workloads_secret] + + # 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 create_user_workloads_config_map(self, + request: Optional[Union[environments.CreateUserWorkloadsConfigMapRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_create_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateUserWorkloadsConfigMapRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsConfigMapRequest, dict]]): + The request object. Create user workloads ConfigMap + request. + parent (:class:`str`): + Required. The environment name to + create a ConfigMap for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_workloads_config_map (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap`): + Required. User workloads ConfigMap to + create. + + This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [parent, user_workloads_config_map] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateUserWorkloadsConfigMapRequest): + request = environments.CreateUserWorkloadsConfigMapRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_workloads_config_map is not None: + request.user_workloads_config_map = user_workloads_config_map + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_user_workloads_config_map] + + # 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 get_user_workloads_config_map(self, + request: Optional[Union[environments.GetUserWorkloadsConfigMapRequest, 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]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_get_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.GetUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsConfigMapRequest, dict]]): + The request object. Get user workloads ConfigMap request. + name (:class:`str`): + Required. The resource name of the + ConfigMap to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" + + 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetUserWorkloadsConfigMapRequest): + request = environments.GetUserWorkloadsConfigMapRequest(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_user_workloads_config_map] + + # 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_user_workloads_config_maps(self, + request: Optional[Union[environments.ListUserWorkloadsConfigMapsRequest, 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.ListUserWorkloadsConfigMapsAsyncPager: + r"""Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_list_user_workloads_config_maps(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ListUserWorkloadsConfigMapsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_config_maps(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest, dict]]): + The request object. List user workloads ConfigMaps + request. + parent (:class:`str`): + Required. List ConfigMaps in the + given environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsConfigMapsAsyncPager: + The user workloads ConfigMaps for a + given environment. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListUserWorkloadsConfigMapsRequest): + request = environments.ListUserWorkloadsConfigMapsRequest(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_user_workloads_config_maps] + + # 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.ListUserWorkloadsConfigMapsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_user_workloads_config_map(self, + request: Optional[Union[environments.UpdateUserWorkloadsConfigMapRequest, dict]] = None, + *, + user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_update_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateUserWorkloadsConfigMapRequest( + ) + + # Make the request + response = await client.update_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsConfigMapRequest, dict]]): + The request object. Update user workloads ConfigMap + request. + user_workloads_config_map (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap`): + Optional. User workloads ConfigMap to + override. + + This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [user_workloads_config_map] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateUserWorkloadsConfigMapRequest): + request = environments.UpdateUserWorkloadsConfigMapRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_workloads_config_map is not None: + request.user_workloads_config_map = user_workloads_config_map + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_user_workloads_config_map] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user_workloads_config_map.name", request.user_workloads_config_map.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_user_workloads_config_map(self, + request: Optional[Union[environments.DeleteUserWorkloadsConfigMapRequest, 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]]] = (), + ) -> None: + r"""Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_delete_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_workloads_config_map(request=request) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsConfigMapRequest, dict]]): + The request object. Delete user workloads ConfigMap + request. + name (:class:`str`): + Required. The ConfigMap to delete, in + the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" + + 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`. + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteUserWorkloadsConfigMapRequest): + request = environments.DeleteUserWorkloadsConfigMapRequest(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_user_workloads_config_map] + + # 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 save_snapshot(self, + request: Optional[Union[environments.SaveSnapshotRequest, dict]] = 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 snapshots of a Cloud Composer environment. + + As a result of this operation, snapshot of environment's + state is stored in a location specified in the + SaveSnapshotRequest. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_save_snapshot(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.SaveSnapshotRequest( + ) + + # Make the request + operation = client.save_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest, dict]]): + The request object. Request to create a snapshot of a + Cloud Composer environment. + 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.orchestration.airflow.service_v1beta1.types.SaveSnapshotResponse` + Response to SaveSnapshotRequest. + + """ + # 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, environments.SaveSnapshotRequest): + request = environments.SaveSnapshotRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.save_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.SaveSnapshotResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def load_snapshot(self, + request: Optional[Union[environments.LoadSnapshotRequest, dict]] = 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"""Loads a snapshot of a Cloud Composer environment. + + As a result of this operation, a snapshot of + environment's specified in LoadSnapshotRequest is loaded + into the environment. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_load_snapshot(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.LoadSnapshotRequest( + ) + + # Make the request + operation = client.load_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest, dict]]): + The request object. Request to load a snapshot into a + Cloud Composer environment. + 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.orchestration.airflow.service_v1beta1.types.LoadSnapshotResponse` + Response to LoadSnapshotRequest. + + """ + # 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, environments.LoadSnapshotRequest): + request = environments.LoadSnapshotRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.load_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.LoadSnapshotResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def database_failover(self, + request: Optional[Union[environments.DatabaseFailoverRequest, dict]] = 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"""Triggers database failover (only for highly resilient + environments). + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_database_failover(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.DatabaseFailoverRequest( + ) + + # Make the request + operation = client.database_failover(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseFailoverRequest, dict]]): + The request object. Request to trigger database failover + (only for highly resilient + environments). + 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.orchestration.airflow.service_v1beta1.types.DatabaseFailoverResponse` + Response for DatabaseFailoverRequest. + + """ + # 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, environments.DatabaseFailoverRequest): + request = environments.DatabaseFailoverRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.database_failover] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.DatabaseFailoverResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + async def fetch_database_properties(self, + request: Optional[Union[environments.FetchDatabasePropertiesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.FetchDatabasePropertiesResponse: + r"""Fetches database properties. + + .. 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.orchestration.airflow import service_v1beta1 + + async def sample_fetch_database_properties(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.FetchDatabasePropertiesRequest( + environment="environment_value", + ) + + # Make the request + response = await client.fetch_database_properties(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesRequest, dict]]): + The request object. Request to fetch properties of + environment's database. + 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.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesResponse: + Response for + FetchDatabasePropertiesRequest. + + """ + # 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, environments.FetchDatabasePropertiesRequest): + request = environments.FetchDatabasePropertiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.fetch_database_properties] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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 __aenter__(self) -> "EnvironmentsAsyncClient": + 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__ = ( + "EnvironmentsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py new file mode 100644 index 000000000000..625e3b410151 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py @@ -0,0 +1,3723 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +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.orchestration.airflow.service_v1beta1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, 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.orchestration.airflow.service_v1beta1.services.environments import pagers +from google.cloud.orchestration.airflow.service_v1beta1.types import environments +from google.cloud.orchestration.airflow.service_v1beta1.types import operations +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 EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EnvironmentsGrpcTransport +from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .transports.rest import EnvironmentsRestTransport + + +class EnvironmentsClientMeta(type): + """Metaclass for the Environments 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[EnvironmentsTransport]] + _transport_registry["grpc"] = EnvironmentsGrpcTransport + _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport + _transport_registry["rest"] = EnvironmentsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[EnvironmentsTransport]: + """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 EnvironmentsClient(metaclass=EnvironmentsClientMeta): + """Managed Apache Airflow Environments.""" + + @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 = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "composer.{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: + EnvironmentsClient: 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: + EnvironmentsClient: 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) -> EnvironmentsTransport: + """Returns the transport used by the client instance. + + Returns: + EnvironmentsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def environment_path(project: str,location: str,environment: str,) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/environments/{environment}".format(project=project, location=location, environment=environment, ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str,str]: + """Parses a environment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_workloads_config_map_path(project: str,location: str,environment: str,user_workloads_config_map: str,) -> str: + """Returns a fully-qualified user_workloads_config_map string.""" + return "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsConfigMaps/{user_workloads_config_map}".format(project=project, location=location, environment=environment, user_workloads_config_map=user_workloads_config_map, ) + + @staticmethod + def parse_user_workloads_config_map_path(path: str) -> Dict[str,str]: + """Parses a user_workloads_config_map path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)/userWorkloadsConfigMaps/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_workloads_secret_path(project: str,location: str,environment: str,user_workloads_secret: str,) -> str: + """Returns a fully-qualified user_workloads_secret string.""" + return "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsSecrets/{user_workloads_secret}".format(project=project, location=location, environment=environment, user_workloads_secret=user_workloads_secret, ) + + @staticmethod + def parse_user_workloads_secret_path(path: str) -> Dict[str,str]: + """Parses a user_workloads_secret path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)/userWorkloadsSecrets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = EnvironmentsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = EnvironmentsClient._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 = EnvironmentsClient._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 + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @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, EnvironmentsTransport, Callable[..., EnvironmentsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the environments 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,EnvironmentsTransport,Callable[..., EnvironmentsTransport]]]): + 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 EnvironmentsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = EnvironmentsClient._read_environment_variables() + self._client_cert_source = EnvironmentsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = EnvironmentsClient._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, EnvironmentsTransport) + if transport_provided: + # transport is a EnvironmentsTransport 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(EnvironmentsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + EnvironmentsClient._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[EnvironmentsTransport], Callable[..., EnvironmentsTransport]] = ( + EnvironmentsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., EnvironmentsTransport], 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.orchestration.airflow.service_v1beta1.EnvironmentsClient`.", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "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.orchestration.airflow.service.v1beta1.Environments", + "credentialsType": None, + } + ) + + def create_environment(self, + request: Optional[Union[environments.CreateEnvironmentRequest, dict]] = None, + *, + parent: Optional[str] = None, + environment: Optional[environments.Environment] = 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"""Create a new environment. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_create_environment(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateEnvironmentRequest( + ) + + # Make the request + operation = client.create_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateEnvironmentRequest, dict]): + The request object. Create a new environment. + parent (str): + The parent must be of the form + "projects/{projectId}/locations/{locationId}". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (google.cloud.orchestration.airflow.service_v1beta1.types.Environment): + The environment to create. + This corresponds to the ``environment`` 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.orchestration.airflow.service_v1beta1.types.Environment` + An environment for running orchestration tasks. + + """ + # 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. + flattened_params = [parent, environment] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateEnvironmentRequest): + request = environments.CreateEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if environment is not None: + request.environment = environment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # 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, + environments.Environment, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_environment(self, + request: Optional[Union[environments.GetEnvironmentRequest, 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]]] = (), + ) -> environments.Environment: + r"""Get an existing environment. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_get_environment(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.GetEnvironmentRequest( + ) + + # Make the request + response = client.get_environment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest, dict]): + The request object. Get an environment. + name (str): + The resource name of the environment + to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1beta1.types.Environment: + An environment for running + orchestration tasks. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetEnvironmentRequest): + request = environments.GetEnvironmentRequest(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_environment] + + # 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_environments(self, + request: Optional[Union[environments.ListEnvironmentsRequest, 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.ListEnvironmentsPager: + r"""List environments. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_list_environments(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.ListEnvironmentsRequest( + ) + + # Make the request + page_result = client.list_environments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest, dict]): + The request object. List environments in a project and + location. + parent (str): + List environments in the given + project and location, in the form: + "projects/{projectId}/locations/{locationId}" + + 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsPager: + The environments in a project and + location. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListEnvironmentsRequest): + request = environments.ListEnvironmentsRequest(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_environments] + + # 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.ListEnvironmentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_environment(self, + request: Optional[Union[environments.UpdateEnvironmentRequest, dict]] = None, + *, + name: Optional[str] = None, + environment: Optional[environments.Environment] = 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"""Update an environment. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_update_environment(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateEnvironmentRequest( + ) + + # Make the request + operation = client.update_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateEnvironmentRequest, dict]): + The request object. Update an environment. + name (str): + The relative resource name of the + environment to update, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + environment (google.cloud.orchestration.airflow.service_v1beta1.types.Environment): + A patch environment. Fields specified by the + ``updateMask`` will be copied from the patch environment + into the environment under update. + + This corresponds to the ``environment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of paths, relative to + ``Environment``, of fields to update. For example, to + set the version of scikit-learn to install in the + environment to 0.19.0 and to remove an existing + installation of argparse, the ``updateMask`` parameter + would include the following two ``paths`` values: + "config.softwareConfig.pypiPackages.scikit-learn" and + "config.softwareConfig.pypiPackages.argparse". The + included patch environment would specify the + scikit-learn version as follows: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "scikit-learn":"==0.19.0" + } + } + } + } + + Note that in the above example, any existing PyPI + packages other than scikit-learn and argparse will be + unaffected. + + Only one update type may be included in a single + request's ``updateMask``. For example, one cannot update + both the PyPI packages and labels in the same request. + However, it is possible to update multiple members of a + map field simultaneously in the same request. For + example, to set the labels "label1" and "label2" while + clearing "label3" (assuming it already exists), one can + provide the paths "labels.label1", "labels.label2", and + "labels.label3" and populate the patch environment as + follows: + + :: + + { + "labels":{ + "label1":"new-label1-value" + "label2":"new-label2-value" + } + } + + Note that in the above example, any existing labels that + are not included in the ``updateMask`` will be + unaffected. + + It is also possible to replace an entire map field by + providing the map field's path in the ``updateMask``. + The new value of the field will be that which is + provided in the patch environment. For example, to + delete all pre-existing user-specified PyPI packages and + install botocore at version 1.7.14, the ``updateMask`` + would contain the path + "config.softwareConfig.pypiPackages", and the patch + environment would be the following: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "botocore":"==1.7.14" + } + } + } + } + + **Note:** Only the following fields can be updated: + + - ``config.softwareConfig.pypiPackages`` + + - Replace all custom custom PyPI packages. If a + replacement package map is not included in + ``environment``, all custom PyPI packages are + cleared. It is an error to provide both this mask + and a mask specifying an individual package. + + - ``config.softwareConfig.pypiPackages.``\ packagename + + - Update the custom PyPI package *packagename*, + preserving other packages. To delete the package, + include it in ``updateMask``, and omit the mapping + for it in + ``environment.config.softwareConfig.pypiPackages``. + It is an error to provide both a mask of this form + and the ``config.softwareConfig.pypiPackages`` + mask. + + - ``labels`` + + - Replace all environment labels. If a replacement + labels map is not included in ``environment``, all + labels are cleared. It is an error to provide both + this mask and a mask specifying one or more + individual labels. + + - ``labels.``\ labelName + + - Set the label named *labelName*, while preserving + other labels. To delete the label, include it in + ``updateMask`` and omit its mapping in + ``environment.labels``. It is an error to provide + both a mask of this form and the ``labels`` mask. + + - ``config.nodeCount`` + + - Horizontally scale the number of nodes in the + environment. An integer greater than or equal to 3 + must be provided in the ``config.nodeCount`` + field. Supported for Cloud Composer environments + in versions composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerNetworkAccessControl`` + + - Replace the environment's current + WebServerNetworkAccessControl. + + - ``config.softwareConfig.airflowConfigOverrides`` + + - Replace all Apache Airflow config overrides. If a + replacement config overrides map is not included + in ``environment``, all config overrides are + cleared. It is an error to provide both this mask + and a mask specifying one or more individual + config overrides. + + - ``config.softwareConfig.airflowConfigOverrides.``\ section-name + + - Override the Apache Airflow config property *name* + in the section named *section*, preserving other + properties. To delete the property override, + include it in ``updateMask`` and omit its mapping + in + ``environment.config.softwareConfig.airflowConfigOverrides``. + It is an error to provide both a mask of this form + and the + ``config.softwareConfig.airflowConfigOverrides`` + mask. + + - ``config.softwareConfig.envVariables`` + + - Replace all environment variables. If a + replacement environment variable map is not + included in ``environment``, all custom + environment variables are cleared. + + - ``config.softwareConfig.imageVersion`` + + - Upgrade the version of the environment in-place. + Refer to ``SoftwareConfig.image_version`` for + information on how to format the new image + version. Additionally, the new image version + cannot effect a version downgrade, and must match + the current image version's Composer and Airflow + major versions. Consult the `Cloud Composer + version + list `__ + for valid values. + + - ``config.softwareConfig.schedulerCount`` + + - Horizontally scale the number of schedulers in + Airflow. A positive integer not greater than the + number of nodes must be provided in the + ``config.softwareConfig.schedulerCount`` field. + Supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-2.*.*. + + - ``config.softwareConfig.cloudDataLineageIntegration`` + + - Configuration for Cloud Data Lineage integration. + + - ``config.databaseConfig.machineType`` + + - Cloud SQL machine type used by Airflow database. + It has to be one of: db-n1-standard-2, + db-n1-standard-4, db-n1-standard-8 or + db-n1-standard-16. Supported for Cloud Composer + environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerConfig.machineType`` + + - Machine type on which Airflow web server is + running. It has to be one of: + composer-n1-webserver-2, composer-n1-webserver-4 + or composer-n1-webserver-8. Supported for Cloud + Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.maintenanceWindow`` + + - Maintenance window during which Cloud Composer + components may be under maintenance. + + - ``config.workloadsConfig`` + + - The workloads configuration settings for the GKE + cluster associated with the Cloud Composer + environment. Supported for Cloud Composer + environments in versions + composer-2.\ *.*-airflow-*.*.\* and newer. + + - ``config.environmentSize`` + + - The size of the Cloud Composer environment. + Supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and + newer. + + 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.orchestration.airflow.service_v1beta1.types.Environment` + An environment for running orchestration tasks. + + """ + # 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. + flattened_params = [name, environment, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateEnvironmentRequest): + request = environments.UpdateEnvironmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if environment is not None: + request.environment = environment + 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_environment] + + # 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, + environments.Environment, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_environment(self, + request: Optional[Union[environments.DeleteEnvironmentRequest, 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"""Delete an environment. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_delete_environment(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteEnvironmentRequest( + ) + + # Make the request + operation = client.delete_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteEnvironmentRequest, dict]): + The request object. Delete an environment. + name (str): + The environment to delete, in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteEnvironmentRequest): + request = environments.DeleteEnvironmentRequest(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_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def restart_web_server(self, + request: Optional[Union[environments.RestartWebServerRequest, dict]] = 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"""Restart Airflow web server. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_restart_web_server(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.RestartWebServerRequest( + ) + + # Make the request + operation = client.restart_web_server(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest, dict]): + The request object. Restart Airflow web server. + retry (google.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.orchestration.airflow.service_v1beta1.types.Environment` + An environment for running orchestration tasks. + + """ + # 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, environments.RestartWebServerRequest): + request = environments.RestartWebServerRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restart_web_server] + + # 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, + environments.Environment, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def check_upgrade(self, + request: Optional[Union[environments.CheckUpgradeRequest, dict]] = 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"""Check if an upgrade operation on the environment will + succeed. + In case of problems detailed info can be found in the + returned 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.orchestration.airflow import service_v1beta1 + + def sample_check_upgrade(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.CheckUpgradeRequest( + ) + + # Make the request + operation = client.check_upgrade(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeRequest, dict]): + The request object. Request to check whether image + upgrade will succeed. + retry (google.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.orchestration.airflow.service_v1beta1.types.CheckUpgradeResponse` Message containing information about the result of an upgrade check + operation. + + """ + # 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, environments.CheckUpgradeRequest): + request = environments.CheckUpgradeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.check_upgrade] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.CheckUpgradeResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def execute_airflow_command(self, + request: Optional[Union[environments.ExecuteAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.ExecuteAirflowCommandResponse: + r"""Executes Airflow CLI command. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_execute_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.ExecuteAirflowCommandRequest( + ) + + # Make the request + response = client.execute_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandRequest, dict]): + The request object. Execute Airflow Command request. + retry (google.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.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandResponse: + Response to + ExecuteAirflowCommandRequest. + + """ + # 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, environments.ExecuteAirflowCommandRequest): + request = environments.ExecuteAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.execute_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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 stop_airflow_command(self, + request: Optional[Union[environments.StopAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.StopAirflowCommandResponse: + r"""Stops Airflow CLI command execution. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_stop_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.StopAirflowCommandRequest( + ) + + # Make the request + response = client.stop_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest, dict]): + The request object. Stop Airflow Command request. + retry (google.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.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse: + Response to + StopAirflowCommandRequest. + + """ + # 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, environments.StopAirflowCommandRequest): + request = environments.StopAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stop_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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 poll_airflow_command(self, + request: Optional[Union[environments.PollAirflowCommandRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.PollAirflowCommandResponse: + r"""Polls Airflow CLI command execution and fetches logs. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_poll_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.PollAirflowCommandRequest( + ) + + # Make the request + response = client.poll_airflow_command(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest, dict]): + The request object. Poll Airflow Command request. + retry (google.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.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse: + Response to + PollAirflowCommandRequest. + + """ + # 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, environments.PollAirflowCommandRequest): + request = environments.PollAirflowCommandRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.poll_airflow_command] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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_workloads(self, + request: Optional[Union[environments.ListWorkloadsRequest, 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.ListWorkloadsPager: + r"""Lists workloads in a Cloud Composer environment. Workload is a + unit that runs a single Composer component. + + This method is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_list_workloads(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest, dict]): + The request object. Request for listing workloads in a + Cloud Composer environment. + parent (str): + Required. The environment name to get + workloads for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListWorkloadsPager: + Response to ListWorkloadsRequest. + + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListWorkloadsRequest): + request = environments.ListWorkloadsRequest(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_workloads] + + # 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.ListWorkloadsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_user_workloads_secret(self, + request: Optional[Union[environments.CreateUserWorkloadsSecretRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_create_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateUserWorkloadsSecretRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsSecretRequest, dict]): + The request object. Create user workloads Secret request. + parent (str): + Required. The environment name to + create a Secret for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_workloads_secret (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret): + Required. User workloads Secret to + create. + + This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [parent, user_workloads_secret] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateUserWorkloadsSecretRequest): + request = environments.CreateUserWorkloadsSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_workloads_secret is not None: + request.user_workloads_secret = user_workloads_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user_workloads_secret] + + # 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 get_user_workloads_secret(self, + request: Optional[Union[environments.GetUserWorkloadsSecretRequest, 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]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Gets an existing user workloads Secret. Values of the "data" + field in the response are cleared. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_get_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.GetUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsSecretRequest, dict]): + The request object. Get user workloads Secret request. + name (str): + Required. The resource name of the + Secret to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" + + 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetUserWorkloadsSecretRequest): + request = environments.GetUserWorkloadsSecretRequest(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_user_workloads_secret] + + # 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_user_workloads_secrets(self, + request: Optional[Union[environments.ListUserWorkloadsSecretsRequest, 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.ListUserWorkloadsSecretsPager: + r"""Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_list_user_workloads_secrets(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.ListUserWorkloadsSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_secrets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest, dict]): + The request object. List user workloads Secrets request. + parent (str): + Required. List Secrets in the given + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsSecretsPager: + The user workloads Secrets for a + given environment. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListUserWorkloadsSecretsRequest): + request = environments.ListUserWorkloadsSecretsRequest(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_user_workloads_secrets] + + # 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.ListUserWorkloadsSecretsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_user_workloads_secret(self, + request: Optional[Union[environments.UpdateUserWorkloadsSecretRequest, dict]] = None, + *, + user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_update_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateUserWorkloadsSecretRequest( + ) + + # Make the request + response = client.update_user_workloads_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsSecretRequest, dict]): + The request object. Update user workloads Secret request. + user_workloads_secret (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret): + Optional. User workloads Secret to + override. + + This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + # 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. + flattened_params = [user_workloads_secret] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateUserWorkloadsSecretRequest): + request = environments.UpdateUserWorkloadsSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_workloads_secret is not None: + request.user_workloads_secret = user_workloads_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_user_workloads_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user_workloads_secret.name", request.user_workloads_secret.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_user_workloads_secret(self, + request: Optional[Union[environments.DeleteUserWorkloadsSecretRequest, 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]]] = (), + ) -> None: + r"""Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_delete_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + client.delete_user_workloads_secret(request=request) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsSecretRequest, dict]): + The request object. Delete user workloads Secret request. + name (str): + Required. The Secret to delete, in + the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" + + 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`. + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteUserWorkloadsSecretRequest): + request = environments.DeleteUserWorkloadsSecretRequest(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_user_workloads_secret] + + # 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 create_user_workloads_config_map(self, + request: Optional[Union[environments.CreateUserWorkloadsConfigMapRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_create_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateUserWorkloadsConfigMapRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsConfigMapRequest, dict]): + The request object. Create user workloads ConfigMap + request. + parent (str): + Required. The environment name to + create a ConfigMap for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_workloads_config_map (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap): + Required. User workloads ConfigMap to + create. + + This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [parent, user_workloads_config_map] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.CreateUserWorkloadsConfigMapRequest): + request = environments.CreateUserWorkloadsConfigMapRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_workloads_config_map is not None: + request.user_workloads_config_map = user_workloads_config_map + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user_workloads_config_map] + + # 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 get_user_workloads_config_map(self, + request: Optional[Union[environments.GetUserWorkloadsConfigMapRequest, 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]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_get_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.GetUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsConfigMapRequest, dict]): + The request object. Get user workloads ConfigMap request. + name (str): + Required. The resource name of the + ConfigMap to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" + + 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.GetUserWorkloadsConfigMapRequest): + request = environments.GetUserWorkloadsConfigMapRequest(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_user_workloads_config_map] + + # 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_user_workloads_config_maps(self, + request: Optional[Union[environments.ListUserWorkloadsConfigMapsRequest, 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.ListUserWorkloadsConfigMapsPager: + r"""Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_list_user_workloads_config_maps(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.ListUserWorkloadsConfigMapsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_config_maps(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest, dict]): + The request object. List user workloads ConfigMaps + request. + parent (str): + Required. List ConfigMaps in the + given environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsConfigMapsPager: + The user workloads ConfigMaps for a + given environment. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.ListUserWorkloadsConfigMapsRequest): + request = environments.ListUserWorkloadsConfigMapsRequest(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_user_workloads_config_maps] + + # 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.ListUserWorkloadsConfigMapsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_user_workloads_config_map(self, + request: Optional[Union[environments.UpdateUserWorkloadsConfigMapRequest, dict]] = None, + *, + user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_update_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateUserWorkloadsConfigMapRequest( + ) + + # Make the request + response = client.update_user_workloads_config_map(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsConfigMapRequest, dict]): + The request object. Update user workloads ConfigMap + request. + user_workloads_config_map (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap): + Optional. User workloads ConfigMap to + override. + + This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + # 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. + flattened_params = [user_workloads_config_map] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.UpdateUserWorkloadsConfigMapRequest): + request = environments.UpdateUserWorkloadsConfigMapRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user_workloads_config_map is not None: + request.user_workloads_config_map = user_workloads_config_map + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_user_workloads_config_map] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user_workloads_config_map.name", request.user_workloads_config_map.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_user_workloads_config_map(self, + request: Optional[Union[environments.DeleteUserWorkloadsConfigMapRequest, 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]]] = (), + ) -> None: + r"""Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_delete_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + client.delete_user_workloads_config_map(request=request) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsConfigMapRequest, dict]): + The request object. Delete user workloads ConfigMap + request. + name (str): + Required. The ConfigMap to delete, in + the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" + + 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`. + """ + # 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. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, environments.DeleteUserWorkloadsConfigMapRequest): + request = environments.DeleteUserWorkloadsConfigMapRequest(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_user_workloads_config_map] + + # 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 save_snapshot(self, + request: Optional[Union[environments.SaveSnapshotRequest, dict]] = 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 snapshots of a Cloud Composer environment. + + As a result of this operation, snapshot of environment's + state is stored in a location specified in the + SaveSnapshotRequest. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_save_snapshot(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.SaveSnapshotRequest( + ) + + # Make the request + operation = client.save_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest, dict]): + The request object. Request to create a snapshot of a + Cloud Composer environment. + retry (google.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.orchestration.airflow.service_v1beta1.types.SaveSnapshotResponse` + Response to SaveSnapshotRequest. + + """ + # 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, environments.SaveSnapshotRequest): + request = environments.SaveSnapshotRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.save_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.SaveSnapshotResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def load_snapshot(self, + request: Optional[Union[environments.LoadSnapshotRequest, dict]] = 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"""Loads a snapshot of a Cloud Composer environment. + + As a result of this operation, a snapshot of + environment's specified in LoadSnapshotRequest is loaded + into the environment. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_load_snapshot(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.LoadSnapshotRequest( + ) + + # Make the request + operation = client.load_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest, dict]): + The request object. Request to load a snapshot into a + Cloud Composer environment. + retry (google.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.orchestration.airflow.service_v1beta1.types.LoadSnapshotResponse` + Response to LoadSnapshotRequest. + + """ + # 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, environments.LoadSnapshotRequest): + request = environments.LoadSnapshotRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.load_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.LoadSnapshotResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def database_failover(self, + request: Optional[Union[environments.DatabaseFailoverRequest, dict]] = 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"""Triggers database failover (only for highly resilient + environments). + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_database_failover(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.DatabaseFailoverRequest( + ) + + # Make the request + operation = client.database_failover(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseFailoverRequest, dict]): + The request object. Request to trigger database failover + (only for highly resilient + environments). + retry (google.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.orchestration.airflow.service_v1beta1.types.DatabaseFailoverResponse` + Response for DatabaseFailoverRequest. + + """ + # 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, environments.DatabaseFailoverRequest): + request = environments.DatabaseFailoverRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.database_failover] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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, + environments.DatabaseFailoverResponse, + metadata_type=operations.OperationMetadata, + ) + + # Done; return the response. + return response + + def fetch_database_properties(self, + request: Optional[Union[environments.FetchDatabasePropertiesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> environments.FetchDatabasePropertiesResponse: + r"""Fetches database properties. + + .. 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.orchestration.airflow import service_v1beta1 + + def sample_fetch_database_properties(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.FetchDatabasePropertiesRequest( + environment="environment_value", + ) + + # Make the request + response = client.fetch_database_properties(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesRequest, dict]): + The request object. Request to fetch properties of + environment's database. + retry (google.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.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesResponse: + Response for + FetchDatabasePropertiesRequest. + + """ + # 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, environments.FetchDatabasePropertiesRequest): + request = environments.FetchDatabasePropertiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_database_properties] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("environment", request.environment), + )), + ) + + # 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) -> "EnvironmentsClient": + 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() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + 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() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + 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,) + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "EnvironmentsClient", +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py new file mode 100644 index 000000000000..3def185aed80 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py @@ -0,0 +1,583 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1.types import environments + + +class ListEnvironmentsPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEnvironments`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse` + 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[..., environments.ListEnvironmentsResponse], + request: environments.ListEnvironmentsRequest, + response: environments.ListEnvironmentsResponse, + *, + 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.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse): + 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 = environments.ListEnvironmentsRequest(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[environments.ListEnvironmentsResponse]: + 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[environments.Environment]: + for page in self.pages: + yield from page.environments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEnvironmentsAsyncPager: + """A pager for iterating through ``list_environments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``environments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEnvironments`` requests and continue to iterate + through the ``environments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse` + 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[environments.ListEnvironmentsResponse]], + request: environments.ListEnvironmentsRequest, + response: environments.ListEnvironmentsResponse, + *, + 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.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse): + 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 = environments.ListEnvironmentsRequest(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[environments.ListEnvironmentsResponse]: + 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[environments.Environment]: + async def async_generator(): + async for page in self.pages: + for response in page.environments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkloadsPager: + """A pager for iterating through ``list_workloads`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workloads`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkloads`` requests and continue to iterate + through the ``workloads`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse` + 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[..., environments.ListWorkloadsResponse], + request: environments.ListWorkloadsRequest, + response: environments.ListWorkloadsResponse, + *, + 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.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse): + 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 = environments.ListWorkloadsRequest(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[environments.ListWorkloadsResponse]: + 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[environments.ListWorkloadsResponse.ComposerWorkload]: + for page in self.pages: + yield from page.workloads + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListWorkloadsAsyncPager: + """A pager for iterating through ``list_workloads`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workloads`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkloads`` requests and continue to iterate + through the ``workloads`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse` + 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[environments.ListWorkloadsResponse]], + request: environments.ListWorkloadsRequest, + response: environments.ListWorkloadsResponse, + *, + 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.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse): + 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 = environments.ListWorkloadsRequest(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[environments.ListWorkloadsResponse]: + 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[environments.ListWorkloadsResponse.ComposerWorkload]: + async def async_generator(): + async for page in self.pages: + for response in page.workloads: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUserWorkloadsSecretsPager: + """A pager for iterating through ``list_user_workloads_secrets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``user_workloads_secrets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUserWorkloadsSecrets`` requests and continue to iterate + through the ``user_workloads_secrets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse` + 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[..., environments.ListUserWorkloadsSecretsResponse], + request: environments.ListUserWorkloadsSecretsRequest, + response: environments.ListUserWorkloadsSecretsResponse, + *, + 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.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse): + 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 = environments.ListUserWorkloadsSecretsRequest(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[environments.ListUserWorkloadsSecretsResponse]: + 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[environments.UserWorkloadsSecret]: + for page in self.pages: + yield from page.user_workloads_secrets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUserWorkloadsSecretsAsyncPager: + """A pager for iterating through ``list_user_workloads_secrets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``user_workloads_secrets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUserWorkloadsSecrets`` requests and continue to iterate + through the ``user_workloads_secrets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse` + 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[environments.ListUserWorkloadsSecretsResponse]], + request: environments.ListUserWorkloadsSecretsRequest, + response: environments.ListUserWorkloadsSecretsResponse, + *, + 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.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse): + 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 = environments.ListUserWorkloadsSecretsRequest(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[environments.ListUserWorkloadsSecretsResponse]: + 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[environments.UserWorkloadsSecret]: + async def async_generator(): + async for page in self.pages: + for response in page.user_workloads_secrets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUserWorkloadsConfigMapsPager: + """A pager for iterating through ``list_user_workloads_config_maps`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``user_workloads_config_maps`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUserWorkloadsConfigMaps`` requests and continue to iterate + through the ``user_workloads_config_maps`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse` + 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[..., environments.ListUserWorkloadsConfigMapsResponse], + request: environments.ListUserWorkloadsConfigMapsRequest, + response: environments.ListUserWorkloadsConfigMapsResponse, + *, + 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.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse): + 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 = environments.ListUserWorkloadsConfigMapsRequest(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[environments.ListUserWorkloadsConfigMapsResponse]: + 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[environments.UserWorkloadsConfigMap]: + for page in self.pages: + yield from page.user_workloads_config_maps + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUserWorkloadsConfigMapsAsyncPager: + """A pager for iterating through ``list_user_workloads_config_maps`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``user_workloads_config_maps`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUserWorkloadsConfigMaps`` requests and continue to iterate + through the ``user_workloads_config_maps`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse` + 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[environments.ListUserWorkloadsConfigMapsResponse]], + request: environments.ListUserWorkloadsConfigMapsRequest, + response: environments.ListUserWorkloadsConfigMapsResponse, + *, + 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.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse): + 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 = environments.ListUserWorkloadsConfigMapsRequest(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[environments.ListUserWorkloadsConfigMapsResponse]: + 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[environments.UserWorkloadsConfigMap]: + async def async_generator(): + async for page in self.pages: + for response in page.user_workloads_config_maps: + 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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/README.rst new file mode 100644 index 000000000000..bce85d4987a6 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`EnvironmentsTransport` is the ABC for all transports. +- public child `EnvironmentsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `EnvironmentsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseEnvironmentsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `EnvironmentsRestTransport` 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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/__init__.py new file mode 100644 index 000000000000..0fb4434d4920 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/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 EnvironmentsTransport +from .grpc import EnvironmentsGrpcTransport +from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport +from .rest import EnvironmentsRestTransport +from .rest import EnvironmentsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] +_transport_registry['grpc'] = EnvironmentsGrpcTransport +_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport +_transport_registry['rest'] = EnvironmentsRestTransport + +__all__ = ( + 'EnvironmentsTransport', + 'EnvironmentsGrpcTransport', + 'EnvironmentsGrpcAsyncIOTransport', + 'EnvironmentsRestTransport', + 'EnvironmentsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py new file mode 100644 index 000000000000..a53951978f34 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py @@ -0,0 +1,540 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.orchestration.airflow.service_v1beta1.types import environments +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class EnvironmentsTransport(abc.ABC): + """Abstract transport class for Environments.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'composer.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: 'composer.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_environment: gapic_v1.method.wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.list_environments: gapic_v1.method.wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.restart_web_server: gapic_v1.method.wrap_method( + self.restart_web_server, + default_timeout=None, + client_info=client_info, + ), + self.check_upgrade: gapic_v1.method.wrap_method( + self.check_upgrade, + default_timeout=None, + client_info=client_info, + ), + self.execute_airflow_command: gapic_v1.method.wrap_method( + self.execute_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.stop_airflow_command: gapic_v1.method.wrap_method( + self.stop_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.poll_airflow_command: gapic_v1.method.wrap_method( + self.poll_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.list_workloads: gapic_v1.method.wrap_method( + self.list_workloads, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_secret: gapic_v1.method.wrap_method( + self.create_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_secret: gapic_v1.method.wrap_method( + self.get_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_secrets: gapic_v1.method.wrap_method( + self.list_user_workloads_secrets, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_secret: gapic_v1.method.wrap_method( + self.update_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_secret: gapic_v1.method.wrap_method( + self.delete_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_config_map: gapic_v1.method.wrap_method( + self.create_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_config_map: gapic_v1.method.wrap_method( + self.get_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_config_maps: gapic_v1.method.wrap_method( + self.list_user_workloads_config_maps, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_config_map: gapic_v1.method.wrap_method( + self.update_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_config_map: gapic_v1.method.wrap_method( + self.delete_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.save_snapshot: gapic_v1.method.wrap_method( + self.save_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.load_snapshot: gapic_v1.method.wrap_method( + self.load_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.database_failover: gapic_v1.method.wrap_method( + self.database_failover, + default_timeout=None, + client_info=client_info, + ), + self.fetch_database_properties: gapic_v1.method.wrap_method( + self.fetch_database_properties, + 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_environment(self) -> Callable[ + [environments.CreateEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_environment(self) -> Callable[ + [environments.GetEnvironmentRequest], + Union[ + environments.Environment, + Awaitable[environments.Environment] + ]]: + raise NotImplementedError() + + @property + def list_environments(self) -> Callable[ + [environments.ListEnvironmentsRequest], + Union[ + environments.ListEnvironmentsResponse, + Awaitable[environments.ListEnvironmentsResponse] + ]]: + raise NotImplementedError() + + @property + def update_environment(self) -> Callable[ + [environments.UpdateEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_environment(self) -> Callable[ + [environments.DeleteEnvironmentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def restart_web_server(self) -> Callable[ + [environments.RestartWebServerRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def check_upgrade(self) -> Callable[ + [environments.CheckUpgradeRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def execute_airflow_command(self) -> Callable[ + [environments.ExecuteAirflowCommandRequest], + Union[ + environments.ExecuteAirflowCommandResponse, + Awaitable[environments.ExecuteAirflowCommandResponse] + ]]: + raise NotImplementedError() + + @property + def stop_airflow_command(self) -> Callable[ + [environments.StopAirflowCommandRequest], + Union[ + environments.StopAirflowCommandResponse, + Awaitable[environments.StopAirflowCommandResponse] + ]]: + raise NotImplementedError() + + @property + def poll_airflow_command(self) -> Callable[ + [environments.PollAirflowCommandRequest], + Union[ + environments.PollAirflowCommandResponse, + Awaitable[environments.PollAirflowCommandResponse] + ]]: + raise NotImplementedError() + + @property + def list_workloads(self) -> Callable[ + [environments.ListWorkloadsRequest], + Union[ + environments.ListWorkloadsResponse, + Awaitable[environments.ListWorkloadsResponse] + ]]: + raise NotImplementedError() + + @property + def create_user_workloads_secret(self) -> Callable[ + [environments.CreateUserWorkloadsSecretRequest], + Union[ + environments.UserWorkloadsSecret, + Awaitable[environments.UserWorkloadsSecret] + ]]: + raise NotImplementedError() + + @property + def get_user_workloads_secret(self) -> Callable[ + [environments.GetUserWorkloadsSecretRequest], + Union[ + environments.UserWorkloadsSecret, + Awaitable[environments.UserWorkloadsSecret] + ]]: + raise NotImplementedError() + + @property + def list_user_workloads_secrets(self) -> Callable[ + [environments.ListUserWorkloadsSecretsRequest], + Union[ + environments.ListUserWorkloadsSecretsResponse, + Awaitable[environments.ListUserWorkloadsSecretsResponse] + ]]: + raise NotImplementedError() + + @property + def update_user_workloads_secret(self) -> Callable[ + [environments.UpdateUserWorkloadsSecretRequest], + Union[ + environments.UserWorkloadsSecret, + Awaitable[environments.UserWorkloadsSecret] + ]]: + raise NotImplementedError() + + @property + def delete_user_workloads_secret(self) -> Callable[ + [environments.DeleteUserWorkloadsSecretRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_user_workloads_config_map(self) -> Callable[ + [environments.CreateUserWorkloadsConfigMapRequest], + Union[ + environments.UserWorkloadsConfigMap, + Awaitable[environments.UserWorkloadsConfigMap] + ]]: + raise NotImplementedError() + + @property + def get_user_workloads_config_map(self) -> Callable[ + [environments.GetUserWorkloadsConfigMapRequest], + Union[ + environments.UserWorkloadsConfigMap, + Awaitable[environments.UserWorkloadsConfigMap] + ]]: + raise NotImplementedError() + + @property + def list_user_workloads_config_maps(self) -> Callable[ + [environments.ListUserWorkloadsConfigMapsRequest], + Union[ + environments.ListUserWorkloadsConfigMapsResponse, + Awaitable[environments.ListUserWorkloadsConfigMapsResponse] + ]]: + raise NotImplementedError() + + @property + def update_user_workloads_config_map(self) -> Callable[ + [environments.UpdateUserWorkloadsConfigMapRequest], + Union[ + environments.UserWorkloadsConfigMap, + Awaitable[environments.UserWorkloadsConfigMap] + ]]: + raise NotImplementedError() + + @property + def delete_user_workloads_config_map(self) -> Callable[ + [environments.DeleteUserWorkloadsConfigMapRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def save_snapshot(self) -> Callable[ + [environments.SaveSnapshotRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def load_snapshot(self) -> Callable[ + [environments.LoadSnapshotRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def database_failover(self) -> Callable[ + [environments.DatabaseFailoverRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def fetch_database_properties(self) -> Callable[ + [environments.FetchDatabasePropertiesRequest], + Union[ + environments.FetchDatabasePropertiesResponse, + Awaitable[environments.FetchDatabasePropertiesResponse] + ]]: + 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 delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'EnvironmentsTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py new file mode 100644 index 000000000000..0c3924547dc3 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py @@ -0,0 +1,1096 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1.types import environments +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, 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.orchestration.airflow.service.v1beta1.Environments", + "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.orchestration.airflow.service.v1beta1.Environments", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EnvironmentsGrpcTransport(EnvironmentsTransport): + """gRPC backend transport for Environments. + + Managed Apache Airflow Environments. + + 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 = 'composer.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: 'composer.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 = 'composer.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_environment(self) -> Callable[ + [environments.CreateEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the create environment method over gRPC. + + Create a new environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['create_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateEnvironment', + request_serializer=environments.CreateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_environment'] + + @property + def get_environment(self) -> Callable[ + [environments.GetEnvironmentRequest], + environments.Environment]: + r"""Return a callable for the get environment method over gRPC. + + Get an existing environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['get_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetEnvironment', + request_serializer=environments.GetEnvironmentRequest.serialize, + response_deserializer=environments.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def list_environments(self) -> Callable[ + [environments.ListEnvironmentsRequest], + environments.ListEnvironmentsResponse]: + r"""Return a callable for the list environments method over gRPC. + + List environments. + + Returns: + Callable[[~.ListEnvironmentsRequest], + ~.ListEnvironmentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environments' not in self._stubs: + self._stubs['list_environments'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListEnvironments', + request_serializer=environments.ListEnvironmentsRequest.serialize, + response_deserializer=environments.ListEnvironmentsResponse.deserialize, + ) + return self._stubs['list_environments'] + + @property + def update_environment(self) -> Callable[ + [environments.UpdateEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the update environment method over gRPC. + + Update an environment. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['update_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateEnvironment', + request_serializer=environments.UpdateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environments.DeleteEnvironmentRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete environment method over gRPC. + + Delete an environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + ~.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_environment' not in self._stubs: + self._stubs['delete_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteEnvironment', + request_serializer=environments.DeleteEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_environment'] + + @property + def restart_web_server(self) -> Callable[ + [environments.RestartWebServerRequest], + operations_pb2.Operation]: + r"""Return a callable for the restart web server method over gRPC. + + Restart Airflow web server. + + Returns: + Callable[[~.RestartWebServerRequest], + ~.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 'restart_web_server' not in self._stubs: + self._stubs['restart_web_server'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/RestartWebServer', + request_serializer=environments.RestartWebServerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restart_web_server'] + + @property + def check_upgrade(self) -> Callable[ + [environments.CheckUpgradeRequest], + operations_pb2.Operation]: + r"""Return a callable for the check upgrade method over gRPC. + + Check if an upgrade operation on the environment will + succeed. + In case of problems detailed info can be found in the + returned Operation. + + Returns: + Callable[[~.CheckUpgradeRequest], + ~.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 'check_upgrade' not in self._stubs: + self._stubs['check_upgrade'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CheckUpgrade', + request_serializer=environments.CheckUpgradeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['check_upgrade'] + + @property + def execute_airflow_command(self) -> Callable[ + [environments.ExecuteAirflowCommandRequest], + environments.ExecuteAirflowCommandResponse]: + r"""Return a callable for the execute airflow command method over gRPC. + + Executes Airflow CLI command. + + Returns: + Callable[[~.ExecuteAirflowCommandRequest], + ~.ExecuteAirflowCommandResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'execute_airflow_command' not in self._stubs: + self._stubs['execute_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ExecuteAirflowCommand', + request_serializer=environments.ExecuteAirflowCommandRequest.serialize, + response_deserializer=environments.ExecuteAirflowCommandResponse.deserialize, + ) + return self._stubs['execute_airflow_command'] + + @property + def stop_airflow_command(self) -> Callable[ + [environments.StopAirflowCommandRequest], + environments.StopAirflowCommandResponse]: + r"""Return a callable for the stop airflow command method over gRPC. + + Stops Airflow CLI command execution. + + Returns: + Callable[[~.StopAirflowCommandRequest], + ~.StopAirflowCommandResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_airflow_command' not in self._stubs: + self._stubs['stop_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/StopAirflowCommand', + request_serializer=environments.StopAirflowCommandRequest.serialize, + response_deserializer=environments.StopAirflowCommandResponse.deserialize, + ) + return self._stubs['stop_airflow_command'] + + @property + def poll_airflow_command(self) -> Callable[ + [environments.PollAirflowCommandRequest], + environments.PollAirflowCommandResponse]: + r"""Return a callable for the poll airflow command method over gRPC. + + Polls Airflow CLI command execution and fetches logs. + + Returns: + Callable[[~.PollAirflowCommandRequest], + ~.PollAirflowCommandResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'poll_airflow_command' not in self._stubs: + self._stubs['poll_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/PollAirflowCommand', + request_serializer=environments.PollAirflowCommandRequest.serialize, + response_deserializer=environments.PollAirflowCommandResponse.deserialize, + ) + return self._stubs['poll_airflow_command'] + + @property + def list_workloads(self) -> Callable[ + [environments.ListWorkloadsRequest], + environments.ListWorkloadsResponse]: + r"""Return a callable for the list workloads method over gRPC. + + Lists workloads in a Cloud Composer environment. Workload is a + unit that runs a single Composer component. + + This method is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + + Returns: + Callable[[~.ListWorkloadsRequest], + ~.ListWorkloadsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workloads' not in self._stubs: + self._stubs['list_workloads'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListWorkloads', + request_serializer=environments.ListWorkloadsRequest.serialize, + response_deserializer=environments.ListWorkloadsResponse.deserialize, + ) + return self._stubs['list_workloads'] + + @property + def create_user_workloads_secret(self) -> Callable[ + [environments.CreateUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + r"""Return a callable for the create user workloads secret method over gRPC. + + Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.CreateUserWorkloadsSecretRequest], + ~.UserWorkloadsSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['create_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateUserWorkloadsSecret', + request_serializer=environments.CreateUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['create_user_workloads_secret'] + + @property + def get_user_workloads_secret(self) -> Callable[ + [environments.GetUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + r"""Return a callable for the get user workloads secret method over gRPC. + + Gets an existing user workloads Secret. Values of the "data" + field in the response are cleared. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.GetUserWorkloadsSecretRequest], + ~.UserWorkloadsSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['get_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetUserWorkloadsSecret', + request_serializer=environments.GetUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['get_user_workloads_secret'] + + @property + def list_user_workloads_secrets(self) -> Callable[ + [environments.ListUserWorkloadsSecretsRequest], + environments.ListUserWorkloadsSecretsResponse]: + r"""Return a callable for the list user workloads secrets method over gRPC. + + Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.ListUserWorkloadsSecretsRequest], + ~.ListUserWorkloadsSecretsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secrets' not in self._stubs: + self._stubs['list_user_workloads_secrets'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListUserWorkloadsSecrets', + request_serializer=environments.ListUserWorkloadsSecretsRequest.serialize, + response_deserializer=environments.ListUserWorkloadsSecretsResponse.deserialize, + ) + return self._stubs['list_user_workloads_secrets'] + + @property + def update_user_workloads_secret(self) -> Callable[ + [environments.UpdateUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + r"""Return a callable for the update user workloads secret method over gRPC. + + Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.UpdateUserWorkloadsSecretRequest], + ~.UserWorkloadsSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['update_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateUserWorkloadsSecret', + request_serializer=environments.UpdateUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['update_user_workloads_secret'] + + @property + def delete_user_workloads_secret(self) -> Callable[ + [environments.DeleteUserWorkloadsSecretRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete user workloads secret method over gRPC. + + Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.DeleteUserWorkloadsSecretRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['delete_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteUserWorkloadsSecret', + request_serializer=environments.DeleteUserWorkloadsSecretRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user_workloads_secret'] + + @property + def create_user_workloads_config_map(self) -> Callable[ + [environments.CreateUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + r"""Return a callable for the create user workloads config + map method over gRPC. + + Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.CreateUserWorkloadsConfigMapRequest], + ~.UserWorkloadsConfigMap]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['create_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateUserWorkloadsConfigMap', + request_serializer=environments.CreateUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['create_user_workloads_config_map'] + + @property + def get_user_workloads_config_map(self) -> Callable[ + [environments.GetUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + r"""Return a callable for the get user workloads config map method over gRPC. + + Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.GetUserWorkloadsConfigMapRequest], + ~.UserWorkloadsConfigMap]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['get_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetUserWorkloadsConfigMap', + request_serializer=environments.GetUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['get_user_workloads_config_map'] + + @property + def list_user_workloads_config_maps(self) -> Callable[ + [environments.ListUserWorkloadsConfigMapsRequest], + environments.ListUserWorkloadsConfigMapsResponse]: + r"""Return a callable for the list user workloads config + maps method over gRPC. + + Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.ListUserWorkloadsConfigMapsRequest], + ~.ListUserWorkloadsConfigMapsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_maps' not in self._stubs: + self._stubs['list_user_workloads_config_maps'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListUserWorkloadsConfigMaps', + request_serializer=environments.ListUserWorkloadsConfigMapsRequest.serialize, + response_deserializer=environments.ListUserWorkloadsConfigMapsResponse.deserialize, + ) + return self._stubs['list_user_workloads_config_maps'] + + @property + def update_user_workloads_config_map(self) -> Callable[ + [environments.UpdateUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + r"""Return a callable for the update user workloads config + map method over gRPC. + + Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.UpdateUserWorkloadsConfigMapRequest], + ~.UserWorkloadsConfigMap]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['update_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateUserWorkloadsConfigMap', + request_serializer=environments.UpdateUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['update_user_workloads_config_map'] + + @property + def delete_user_workloads_config_map(self) -> Callable[ + [environments.DeleteUserWorkloadsConfigMapRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete user workloads config + map method over gRPC. + + Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.DeleteUserWorkloadsConfigMapRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['delete_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteUserWorkloadsConfigMap', + request_serializer=environments.DeleteUserWorkloadsConfigMapRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user_workloads_config_map'] + + @property + def save_snapshot(self) -> Callable[ + [environments.SaveSnapshotRequest], + operations_pb2.Operation]: + r"""Return a callable for the save snapshot method over gRPC. + + Creates a snapshots of a Cloud Composer environment. + + As a result of this operation, snapshot of environment's + state is stored in a location specified in the + SaveSnapshotRequest. + + Returns: + Callable[[~.SaveSnapshotRequest], + ~.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 'save_snapshot' not in self._stubs: + self._stubs['save_snapshot'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/SaveSnapshot', + request_serializer=environments.SaveSnapshotRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['save_snapshot'] + + @property + def load_snapshot(self) -> Callable[ + [environments.LoadSnapshotRequest], + operations_pb2.Operation]: + r"""Return a callable for the load snapshot method over gRPC. + + Loads a snapshot of a Cloud Composer environment. + + As a result of this operation, a snapshot of + environment's specified in LoadSnapshotRequest is loaded + into the environment. + + Returns: + Callable[[~.LoadSnapshotRequest], + ~.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 'load_snapshot' not in self._stubs: + self._stubs['load_snapshot'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/LoadSnapshot', + request_serializer=environments.LoadSnapshotRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['load_snapshot'] + + @property + def database_failover(self) -> Callable[ + [environments.DatabaseFailoverRequest], + operations_pb2.Operation]: + r"""Return a callable for the database failover method over gRPC. + + Triggers database failover (only for highly resilient + environments). + + Returns: + Callable[[~.DatabaseFailoverRequest], + ~.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 'database_failover' not in self._stubs: + self._stubs['database_failover'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DatabaseFailover', + request_serializer=environments.DatabaseFailoverRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['database_failover'] + + @property + def fetch_database_properties(self) -> Callable[ + [environments.FetchDatabasePropertiesRequest], + environments.FetchDatabasePropertiesResponse]: + r"""Return a callable for the fetch database properties method over gRPC. + + Fetches database properties. + + Returns: + Callable[[~.FetchDatabasePropertiesRequest], + ~.FetchDatabasePropertiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fetch_database_properties' not in self._stubs: + self._stubs['fetch_database_properties'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/FetchDatabaseProperties', + request_serializer=environments.FetchDatabasePropertiesRequest.serialize, + response_deserializer=environments.FetchDatabasePropertiesResponse.deserialize, + ) + return self._stubs['fetch_database_properties'] + + 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 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__ = ( + 'EnvironmentsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py new file mode 100644 index 000000000000..02072338d533 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py @@ -0,0 +1,1251 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1.types import environments +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import EnvironmentsGrpcTransport + +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.orchestration.airflow.service.v1beta1.Environments", + "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.orchestration.airflow.service.v1beta1.Environments", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): + """gRPC AsyncIO backend transport for Environments. + + Managed Apache Airflow Environments. + + 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 = 'composer.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 = 'composer.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: 'composer.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_environment(self) -> Callable[ + [environments.CreateEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create environment method over gRPC. + + Create a new environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['create_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateEnvironment', + request_serializer=environments.CreateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_environment'] + + @property + def get_environment(self) -> Callable[ + [environments.GetEnvironmentRequest], + Awaitable[environments.Environment]]: + r"""Return a callable for the get environment method over gRPC. + + Get an existing environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environment' not in self._stubs: + self._stubs['get_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetEnvironment', + request_serializer=environments.GetEnvironmentRequest.serialize, + response_deserializer=environments.Environment.deserialize, + ) + return self._stubs['get_environment'] + + @property + def list_environments(self) -> Callable[ + [environments.ListEnvironmentsRequest], + Awaitable[environments.ListEnvironmentsResponse]]: + r"""Return a callable for the list environments method over gRPC. + + List environments. + + Returns: + Callable[[~.ListEnvironmentsRequest], + Awaitable[~.ListEnvironmentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_environments' not in self._stubs: + self._stubs['list_environments'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListEnvironments', + request_serializer=environments.ListEnvironmentsRequest.serialize, + response_deserializer=environments.ListEnvironmentsResponse.deserialize, + ) + return self._stubs['list_environments'] + + @property + def update_environment(self) -> Callable[ + [environments.UpdateEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update environment method over gRPC. + + Update an environment. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['update_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateEnvironment', + request_serializer=environments.UpdateEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_environment'] + + @property + def delete_environment(self) -> Callable[ + [environments.DeleteEnvironmentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete environment method over gRPC. + + Delete an environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + 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_environment' not in self._stubs: + self._stubs['delete_environment'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteEnvironment', + request_serializer=environments.DeleteEnvironmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_environment'] + + @property + def restart_web_server(self) -> Callable[ + [environments.RestartWebServerRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the restart web server method over gRPC. + + Restart Airflow web server. + + Returns: + Callable[[~.RestartWebServerRequest], + 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 'restart_web_server' not in self._stubs: + self._stubs['restart_web_server'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/RestartWebServer', + request_serializer=environments.RestartWebServerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['restart_web_server'] + + @property + def check_upgrade(self) -> Callable[ + [environments.CheckUpgradeRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the check upgrade method over gRPC. + + Check if an upgrade operation on the environment will + succeed. + In case of problems detailed info can be found in the + returned Operation. + + Returns: + Callable[[~.CheckUpgradeRequest], + 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 'check_upgrade' not in self._stubs: + self._stubs['check_upgrade'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CheckUpgrade', + request_serializer=environments.CheckUpgradeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['check_upgrade'] + + @property + def execute_airflow_command(self) -> Callable[ + [environments.ExecuteAirflowCommandRequest], + Awaitable[environments.ExecuteAirflowCommandResponse]]: + r"""Return a callable for the execute airflow command method over gRPC. + + Executes Airflow CLI command. + + Returns: + Callable[[~.ExecuteAirflowCommandRequest], + Awaitable[~.ExecuteAirflowCommandResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'execute_airflow_command' not in self._stubs: + self._stubs['execute_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ExecuteAirflowCommand', + request_serializer=environments.ExecuteAirflowCommandRequest.serialize, + response_deserializer=environments.ExecuteAirflowCommandResponse.deserialize, + ) + return self._stubs['execute_airflow_command'] + + @property + def stop_airflow_command(self) -> Callable[ + [environments.StopAirflowCommandRequest], + Awaitable[environments.StopAirflowCommandResponse]]: + r"""Return a callable for the stop airflow command method over gRPC. + + Stops Airflow CLI command execution. + + Returns: + Callable[[~.StopAirflowCommandRequest], + Awaitable[~.StopAirflowCommandResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'stop_airflow_command' not in self._stubs: + self._stubs['stop_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/StopAirflowCommand', + request_serializer=environments.StopAirflowCommandRequest.serialize, + response_deserializer=environments.StopAirflowCommandResponse.deserialize, + ) + return self._stubs['stop_airflow_command'] + + @property + def poll_airflow_command(self) -> Callable[ + [environments.PollAirflowCommandRequest], + Awaitable[environments.PollAirflowCommandResponse]]: + r"""Return a callable for the poll airflow command method over gRPC. + + Polls Airflow CLI command execution and fetches logs. + + Returns: + Callable[[~.PollAirflowCommandRequest], + Awaitable[~.PollAirflowCommandResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'poll_airflow_command' not in self._stubs: + self._stubs['poll_airflow_command'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/PollAirflowCommand', + request_serializer=environments.PollAirflowCommandRequest.serialize, + response_deserializer=environments.PollAirflowCommandResponse.deserialize, + ) + return self._stubs['poll_airflow_command'] + + @property + def list_workloads(self) -> Callable[ + [environments.ListWorkloadsRequest], + Awaitable[environments.ListWorkloadsResponse]]: + r"""Return a callable for the list workloads method over gRPC. + + Lists workloads in a Cloud Composer environment. Workload is a + unit that runs a single Composer component. + + This method is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + + Returns: + Callable[[~.ListWorkloadsRequest], + Awaitable[~.ListWorkloadsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_workloads' not in self._stubs: + self._stubs['list_workloads'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListWorkloads', + request_serializer=environments.ListWorkloadsRequest.serialize, + response_deserializer=environments.ListWorkloadsResponse.deserialize, + ) + return self._stubs['list_workloads'] + + @property + def create_user_workloads_secret(self) -> Callable[ + [environments.CreateUserWorkloadsSecretRequest], + Awaitable[environments.UserWorkloadsSecret]]: + r"""Return a callable for the create user workloads secret method over gRPC. + + Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.CreateUserWorkloadsSecretRequest], + Awaitable[~.UserWorkloadsSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['create_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateUserWorkloadsSecret', + request_serializer=environments.CreateUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['create_user_workloads_secret'] + + @property + def get_user_workloads_secret(self) -> Callable[ + [environments.GetUserWorkloadsSecretRequest], + Awaitable[environments.UserWorkloadsSecret]]: + r"""Return a callable for the get user workloads secret method over gRPC. + + Gets an existing user workloads Secret. Values of the "data" + field in the response are cleared. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.GetUserWorkloadsSecretRequest], + Awaitable[~.UserWorkloadsSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['get_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetUserWorkloadsSecret', + request_serializer=environments.GetUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['get_user_workloads_secret'] + + @property + def list_user_workloads_secrets(self) -> Callable[ + [environments.ListUserWorkloadsSecretsRequest], + Awaitable[environments.ListUserWorkloadsSecretsResponse]]: + r"""Return a callable for the list user workloads secrets method over gRPC. + + Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.ListUserWorkloadsSecretsRequest], + Awaitable[~.ListUserWorkloadsSecretsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secrets' not in self._stubs: + self._stubs['list_user_workloads_secrets'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListUserWorkloadsSecrets', + request_serializer=environments.ListUserWorkloadsSecretsRequest.serialize, + response_deserializer=environments.ListUserWorkloadsSecretsResponse.deserialize, + ) + return self._stubs['list_user_workloads_secrets'] + + @property + def update_user_workloads_secret(self) -> Callable[ + [environments.UpdateUserWorkloadsSecretRequest], + Awaitable[environments.UserWorkloadsSecret]]: + r"""Return a callable for the update user workloads secret method over gRPC. + + Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.UpdateUserWorkloadsSecretRequest], + Awaitable[~.UserWorkloadsSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['update_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateUserWorkloadsSecret', + request_serializer=environments.UpdateUserWorkloadsSecretRequest.serialize, + response_deserializer=environments.UserWorkloadsSecret.deserialize, + ) + return self._stubs['update_user_workloads_secret'] + + @property + def delete_user_workloads_secret(self) -> Callable[ + [environments.DeleteUserWorkloadsSecretRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete user workloads secret method over gRPC. + + Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.DeleteUserWorkloadsSecretRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: + self._stubs['delete_user_workloads_secret'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteUserWorkloadsSecret', + request_serializer=environments.DeleteUserWorkloadsSecretRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user_workloads_secret'] + + @property + def create_user_workloads_config_map(self) -> Callable[ + [environments.CreateUserWorkloadsConfigMapRequest], + Awaitable[environments.UserWorkloadsConfigMap]]: + r"""Return a callable for the create user workloads config + map method over gRPC. + + Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.CreateUserWorkloadsConfigMapRequest], + Awaitable[~.UserWorkloadsConfigMap]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['create_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateUserWorkloadsConfigMap', + request_serializer=environments.CreateUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['create_user_workloads_config_map'] + + @property + def get_user_workloads_config_map(self) -> Callable[ + [environments.GetUserWorkloadsConfigMapRequest], + Awaitable[environments.UserWorkloadsConfigMap]]: + r"""Return a callable for the get user workloads config map method over gRPC. + + Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.GetUserWorkloadsConfigMapRequest], + Awaitable[~.UserWorkloadsConfigMap]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['get_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetUserWorkloadsConfigMap', + request_serializer=environments.GetUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['get_user_workloads_config_map'] + + @property + def list_user_workloads_config_maps(self) -> Callable[ + [environments.ListUserWorkloadsConfigMapsRequest], + Awaitable[environments.ListUserWorkloadsConfigMapsResponse]]: + r"""Return a callable for the list user workloads config + maps method over gRPC. + + Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.ListUserWorkloadsConfigMapsRequest], + Awaitable[~.ListUserWorkloadsConfigMapsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_maps' not in self._stubs: + self._stubs['list_user_workloads_config_maps'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListUserWorkloadsConfigMaps', + request_serializer=environments.ListUserWorkloadsConfigMapsRequest.serialize, + response_deserializer=environments.ListUserWorkloadsConfigMapsResponse.deserialize, + ) + return self._stubs['list_user_workloads_config_maps'] + + @property + def update_user_workloads_config_map(self) -> Callable[ + [environments.UpdateUserWorkloadsConfigMapRequest], + Awaitable[environments.UserWorkloadsConfigMap]]: + r"""Return a callable for the update user workloads config + map method over gRPC. + + Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.UpdateUserWorkloadsConfigMapRequest], + Awaitable[~.UserWorkloadsConfigMap]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['update_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateUserWorkloadsConfigMap', + request_serializer=environments.UpdateUserWorkloadsConfigMapRequest.serialize, + response_deserializer=environments.UserWorkloadsConfigMap.deserialize, + ) + return self._stubs['update_user_workloads_config_map'] + + @property + def delete_user_workloads_config_map(self) -> Callable[ + [environments.DeleteUserWorkloadsConfigMapRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete user workloads config + map method over gRPC. + + Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + + Returns: + Callable[[~.DeleteUserWorkloadsConfigMapRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: + self._stubs['delete_user_workloads_config_map'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteUserWorkloadsConfigMap', + request_serializer=environments.DeleteUserWorkloadsConfigMapRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user_workloads_config_map'] + + @property + def save_snapshot(self) -> Callable[ + [environments.SaveSnapshotRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the save snapshot method over gRPC. + + Creates a snapshots of a Cloud Composer environment. + + As a result of this operation, snapshot of environment's + state is stored in a location specified in the + SaveSnapshotRequest. + + Returns: + Callable[[~.SaveSnapshotRequest], + 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 'save_snapshot' not in self._stubs: + self._stubs['save_snapshot'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/SaveSnapshot', + request_serializer=environments.SaveSnapshotRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['save_snapshot'] + + @property + def load_snapshot(self) -> Callable[ + [environments.LoadSnapshotRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the load snapshot method over gRPC. + + Loads a snapshot of a Cloud Composer environment. + + As a result of this operation, a snapshot of + environment's specified in LoadSnapshotRequest is loaded + into the environment. + + Returns: + Callable[[~.LoadSnapshotRequest], + 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 'load_snapshot' not in self._stubs: + self._stubs['load_snapshot'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/LoadSnapshot', + request_serializer=environments.LoadSnapshotRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['load_snapshot'] + + @property + def database_failover(self) -> Callable[ + [environments.DatabaseFailoverRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the database failover method over gRPC. + + Triggers database failover (only for highly resilient + environments). + + Returns: + Callable[[~.DatabaseFailoverRequest], + 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 'database_failover' not in self._stubs: + self._stubs['database_failover'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DatabaseFailover', + request_serializer=environments.DatabaseFailoverRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['database_failover'] + + @property + def fetch_database_properties(self) -> Callable[ + [environments.FetchDatabasePropertiesRequest], + Awaitable[environments.FetchDatabasePropertiesResponse]]: + r"""Return a callable for the fetch database properties method over gRPC. + + Fetches database properties. + + Returns: + Callable[[~.FetchDatabasePropertiesRequest], + Awaitable[~.FetchDatabasePropertiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fetch_database_properties' not in self._stubs: + self._stubs['fetch_database_properties'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.Environments/FetchDatabaseProperties', + request_serializer=environments.FetchDatabasePropertiesRequest.serialize, + response_deserializer=environments.FetchDatabasePropertiesResponse.deserialize, + ) + return self._stubs['fetch_database_properties'] + + 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_environment: self._wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: self._wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.list_environments: self._wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: self._wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: self._wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.restart_web_server: self._wrap_method( + self.restart_web_server, + default_timeout=None, + client_info=client_info, + ), + self.check_upgrade: self._wrap_method( + self.check_upgrade, + default_timeout=None, + client_info=client_info, + ), + self.execute_airflow_command: self._wrap_method( + self.execute_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.stop_airflow_command: self._wrap_method( + self.stop_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.poll_airflow_command: self._wrap_method( + self.poll_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.list_workloads: self._wrap_method( + self.list_workloads, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_secret: self._wrap_method( + self.create_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_secret: self._wrap_method( + self.get_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_secrets: self._wrap_method( + self.list_user_workloads_secrets, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_secret: self._wrap_method( + self.update_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_secret: self._wrap_method( + self.delete_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_config_map: self._wrap_method( + self.create_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_config_map: self._wrap_method( + self.get_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_config_maps: self._wrap_method( + self.list_user_workloads_config_maps, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_config_map: self._wrap_method( + self.update_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_config_map: self._wrap_method( + self.delete_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.save_snapshot: self._wrap_method( + self.save_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.load_snapshot: self._wrap_method( + self.load_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.database_failover: self._wrap_method( + self.database_failover, + default_timeout=None, + client_info=client_info, + ), + self.fetch_database_properties: self._wrap_method( + self.fetch_database_properties, + 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 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__ = ( + 'EnvironmentsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py new file mode 100644 index 000000000000..f29b846f82fe --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py @@ -0,0 +1,4862 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1.types import environments +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseEnvironmentsRestTransport +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 EnvironmentsRestInterceptor: + """Interceptor for Environments. + + 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 EnvironmentsRestTransport. + + .. code-block:: python + class MyCustomEnvironmentsInterceptor(EnvironmentsRestInterceptor): + def pre_check_upgrade(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_check_upgrade(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_environment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_environment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_user_workloads_config_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user_workloads_config_map(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_user_workloads_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user_workloads_secret(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_database_failover(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_database_failover(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_environment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_environment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_user_workloads_config_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_user_workloads_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_execute_airflow_command(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_execute_airflow_command(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_database_properties(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_database_properties(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_environment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_environment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_user_workloads_config_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user_workloads_config_map(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_user_workloads_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user_workloads_secret(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_environments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_environments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_user_workloads_config_maps(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_user_workloads_config_maps(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_user_workloads_secrets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_user_workloads_secrets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workloads(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workloads(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_load_snapshot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_load_snapshot(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_poll_airflow_command(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_poll_airflow_command(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restart_web_server(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restart_web_server(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_save_snapshot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_save_snapshot(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_airflow_command(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_airflow_command(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_environment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_environment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user_workloads_config_map(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user_workloads_config_map(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user_workloads_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user_workloads_secret(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EnvironmentsRestTransport(interceptor=MyCustomEnvironmentsInterceptor()) + client = EnvironmentsClient(transport=transport) + + + """ + def pre_check_upgrade(self, request: environments.CheckUpgradeRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CheckUpgradeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for check_upgrade + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_check_upgrade(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for check_upgrade + + DEPRECATED. Please use the `post_check_upgrade_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_check_upgrade` interceptor runs + before the `post_check_upgrade_with_metadata` interceptor. + """ + return response + + def post_check_upgrade_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for check_upgrade + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_check_upgrade_with_metadata` + interceptor in new development instead of the `post_check_upgrade` interceptor. + When both interceptors are used, this `post_check_upgrade_with_metadata` interceptor runs after the + `post_check_upgrade` interceptor. The (possibly modified) response returned by + `post_check_upgrade` will be passed to + `post_check_upgrade_with_metadata`. + """ + return response, metadata + + def pre_create_environment(self, request: environments.CreateEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_environment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_create_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_environment + + DEPRECATED. Please use the `post_create_environment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_create_environment` interceptor runs + before the `post_create_environment_with_metadata` interceptor. + """ + return response + + def post_create_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_environment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_create_environment_with_metadata` + interceptor in new development instead of the `post_create_environment` interceptor. + When both interceptors are used, this `post_create_environment_with_metadata` interceptor runs after the + `post_create_environment` interceptor. The (possibly modified) response returned by + `post_create_environment` will be passed to + `post_create_environment_with_metadata`. + """ + return response, metadata + + def pre_create_user_workloads_config_map(self, request: environments.CreateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_user_workloads_config_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_create_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: + """Post-rpc interceptor for create_user_workloads_config_map + + DEPRECATED. Please use the `post_create_user_workloads_config_map_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_create_user_workloads_config_map` interceptor runs + before the `post_create_user_workloads_config_map_with_metadata` interceptor. + """ + return response + + def post_create_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_user_workloads_config_map + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_create_user_workloads_config_map_with_metadata` + interceptor in new development instead of the `post_create_user_workloads_config_map` interceptor. + When both interceptors are used, this `post_create_user_workloads_config_map_with_metadata` interceptor runs after the + `post_create_user_workloads_config_map` interceptor. The (possibly modified) response returned by + `post_create_user_workloads_config_map` will be passed to + `post_create_user_workloads_config_map_with_metadata`. + """ + return response, metadata + + def pre_create_user_workloads_secret(self, request: environments.CreateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_user_workloads_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_create_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: + """Post-rpc interceptor for create_user_workloads_secret + + DEPRECATED. Please use the `post_create_user_workloads_secret_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_create_user_workloads_secret` interceptor runs + before the `post_create_user_workloads_secret_with_metadata` interceptor. + """ + return response + + def post_create_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_user_workloads_secret + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_create_user_workloads_secret_with_metadata` + interceptor in new development instead of the `post_create_user_workloads_secret` interceptor. + When both interceptors are used, this `post_create_user_workloads_secret_with_metadata` interceptor runs after the + `post_create_user_workloads_secret` interceptor. The (possibly modified) response returned by + `post_create_user_workloads_secret` will be passed to + `post_create_user_workloads_secret_with_metadata`. + """ + return response, metadata + + def pre_database_failover(self, request: environments.DatabaseFailoverRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DatabaseFailoverRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for database_failover + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_database_failover(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for database_failover + + DEPRECATED. Please use the `post_database_failover_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_database_failover` interceptor runs + before the `post_database_failover_with_metadata` interceptor. + """ + return response + + def post_database_failover_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for database_failover + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_database_failover_with_metadata` + interceptor in new development instead of the `post_database_failover` interceptor. + When both interceptors are used, this `post_database_failover_with_metadata` interceptor runs after the + `post_database_failover` interceptor. The (possibly modified) response returned by + `post_database_failover` will be passed to + `post_database_failover_with_metadata`. + """ + return response, metadata + + def pre_delete_environment(self, request: environments.DeleteEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_environment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_delete_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_environment + + DEPRECATED. Please use the `post_delete_environment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_delete_environment` interceptor runs + before the `post_delete_environment_with_metadata` interceptor. + """ + return response + + def post_delete_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_environment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_delete_environment_with_metadata` + interceptor in new development instead of the `post_delete_environment` interceptor. + When both interceptors are used, this `post_delete_environment_with_metadata` interceptor runs after the + `post_delete_environment` interceptor. The (possibly modified) response returned by + `post_delete_environment` will be passed to + `post_delete_environment_with_metadata`. + """ + return response, metadata + + def pre_delete_user_workloads_config_map(self, request: environments.DeleteUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_user_workloads_config_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def pre_delete_user_workloads_secret(self, request: environments.DeleteUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_user_workloads_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def pre_execute_airflow_command(self, request: environments.ExecuteAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ExecuteAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for execute_airflow_command + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_execute_airflow_command(self, response: environments.ExecuteAirflowCommandResponse) -> environments.ExecuteAirflowCommandResponse: + """Post-rpc interceptor for execute_airflow_command + + DEPRECATED. Please use the `post_execute_airflow_command_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_execute_airflow_command` interceptor runs + before the `post_execute_airflow_command_with_metadata` interceptor. + """ + return response + + def post_execute_airflow_command_with_metadata(self, response: environments.ExecuteAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ExecuteAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for execute_airflow_command + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_execute_airflow_command_with_metadata` + interceptor in new development instead of the `post_execute_airflow_command` interceptor. + When both interceptors are used, this `post_execute_airflow_command_with_metadata` interceptor runs after the + `post_execute_airflow_command` interceptor. The (possibly modified) response returned by + `post_execute_airflow_command` will be passed to + `post_execute_airflow_command_with_metadata`. + """ + return response, metadata + + def pre_fetch_database_properties(self, request: environments.FetchDatabasePropertiesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.FetchDatabasePropertiesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for fetch_database_properties + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_fetch_database_properties(self, response: environments.FetchDatabasePropertiesResponse) -> environments.FetchDatabasePropertiesResponse: + """Post-rpc interceptor for fetch_database_properties + + DEPRECATED. Please use the `post_fetch_database_properties_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_fetch_database_properties` interceptor runs + before the `post_fetch_database_properties_with_metadata` interceptor. + """ + return response + + def post_fetch_database_properties_with_metadata(self, response: environments.FetchDatabasePropertiesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.FetchDatabasePropertiesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for fetch_database_properties + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_fetch_database_properties_with_metadata` + interceptor in new development instead of the `post_fetch_database_properties` interceptor. + When both interceptors are used, this `post_fetch_database_properties_with_metadata` interceptor runs after the + `post_fetch_database_properties` interceptor. The (possibly modified) response returned by + `post_fetch_database_properties` will be passed to + `post_fetch_database_properties_with_metadata`. + """ + return response, metadata + + def pre_get_environment(self, request: environments.GetEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_environment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_get_environment(self, response: environments.Environment) -> environments.Environment: + """Post-rpc interceptor for get_environment + + DEPRECATED. Please use the `post_get_environment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_get_environment` interceptor runs + before the `post_get_environment_with_metadata` interceptor. + """ + return response + + def post_get_environment_with_metadata(self, response: environments.Environment, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.Environment, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_environment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_get_environment_with_metadata` + interceptor in new development instead of the `post_get_environment` interceptor. + When both interceptors are used, this `post_get_environment_with_metadata` interceptor runs after the + `post_get_environment` interceptor. The (possibly modified) response returned by + `post_get_environment` will be passed to + `post_get_environment_with_metadata`. + """ + return response, metadata + + def pre_get_user_workloads_config_map(self, request: environments.GetUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_user_workloads_config_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_get_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: + """Post-rpc interceptor for get_user_workloads_config_map + + DEPRECATED. Please use the `post_get_user_workloads_config_map_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_get_user_workloads_config_map` interceptor runs + before the `post_get_user_workloads_config_map_with_metadata` interceptor. + """ + return response + + def post_get_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_user_workloads_config_map + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_get_user_workloads_config_map_with_metadata` + interceptor in new development instead of the `post_get_user_workloads_config_map` interceptor. + When both interceptors are used, this `post_get_user_workloads_config_map_with_metadata` interceptor runs after the + `post_get_user_workloads_config_map` interceptor. The (possibly modified) response returned by + `post_get_user_workloads_config_map` will be passed to + `post_get_user_workloads_config_map_with_metadata`. + """ + return response, metadata + + def pre_get_user_workloads_secret(self, request: environments.GetUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_user_workloads_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_get_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: + """Post-rpc interceptor for get_user_workloads_secret + + DEPRECATED. Please use the `post_get_user_workloads_secret_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_get_user_workloads_secret` interceptor runs + before the `post_get_user_workloads_secret_with_metadata` interceptor. + """ + return response + + def post_get_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_user_workloads_secret + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_get_user_workloads_secret_with_metadata` + interceptor in new development instead of the `post_get_user_workloads_secret` interceptor. + When both interceptors are used, this `post_get_user_workloads_secret_with_metadata` interceptor runs after the + `post_get_user_workloads_secret` interceptor. The (possibly modified) response returned by + `post_get_user_workloads_secret` will be passed to + `post_get_user_workloads_secret_with_metadata`. + """ + return response, metadata + + def pre_list_environments(self, request: environments.ListEnvironmentsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListEnvironmentsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_environments + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_list_environments(self, response: environments.ListEnvironmentsResponse) -> environments.ListEnvironmentsResponse: + """Post-rpc interceptor for list_environments + + DEPRECATED. Please use the `post_list_environments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_list_environments` interceptor runs + before the `post_list_environments_with_metadata` interceptor. + """ + return response + + def post_list_environments_with_metadata(self, response: environments.ListEnvironmentsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListEnvironmentsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_environments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_list_environments_with_metadata` + interceptor in new development instead of the `post_list_environments` interceptor. + When both interceptors are used, this `post_list_environments_with_metadata` interceptor runs after the + `post_list_environments` interceptor. The (possibly modified) response returned by + `post_list_environments` will be passed to + `post_list_environments_with_metadata`. + """ + return response, metadata + + def pre_list_user_workloads_config_maps(self, request: environments.ListUserWorkloadsConfigMapsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsConfigMapsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_user_workloads_config_maps + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_list_user_workloads_config_maps(self, response: environments.ListUserWorkloadsConfigMapsResponse) -> environments.ListUserWorkloadsConfigMapsResponse: + """Post-rpc interceptor for list_user_workloads_config_maps + + DEPRECATED. Please use the `post_list_user_workloads_config_maps_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_list_user_workloads_config_maps` interceptor runs + before the `post_list_user_workloads_config_maps_with_metadata` interceptor. + """ + return response + + def post_list_user_workloads_config_maps_with_metadata(self, response: environments.ListUserWorkloadsConfigMapsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsConfigMapsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_user_workloads_config_maps + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_list_user_workloads_config_maps_with_metadata` + interceptor in new development instead of the `post_list_user_workloads_config_maps` interceptor. + When both interceptors are used, this `post_list_user_workloads_config_maps_with_metadata` interceptor runs after the + `post_list_user_workloads_config_maps` interceptor. The (possibly modified) response returned by + `post_list_user_workloads_config_maps` will be passed to + `post_list_user_workloads_config_maps_with_metadata`. + """ + return response, metadata + + def pre_list_user_workloads_secrets(self, request: environments.ListUserWorkloadsSecretsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsSecretsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_user_workloads_secrets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_list_user_workloads_secrets(self, response: environments.ListUserWorkloadsSecretsResponse) -> environments.ListUserWorkloadsSecretsResponse: + """Post-rpc interceptor for list_user_workloads_secrets + + DEPRECATED. Please use the `post_list_user_workloads_secrets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_list_user_workloads_secrets` interceptor runs + before the `post_list_user_workloads_secrets_with_metadata` interceptor. + """ + return response + + def post_list_user_workloads_secrets_with_metadata(self, response: environments.ListUserWorkloadsSecretsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsSecretsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_user_workloads_secrets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_list_user_workloads_secrets_with_metadata` + interceptor in new development instead of the `post_list_user_workloads_secrets` interceptor. + When both interceptors are used, this `post_list_user_workloads_secrets_with_metadata` interceptor runs after the + `post_list_user_workloads_secrets` interceptor. The (possibly modified) response returned by + `post_list_user_workloads_secrets` will be passed to + `post_list_user_workloads_secrets_with_metadata`. + """ + return response, metadata + + def pre_list_workloads(self, request: environments.ListWorkloadsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListWorkloadsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_workloads + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_list_workloads(self, response: environments.ListWorkloadsResponse) -> environments.ListWorkloadsResponse: + """Post-rpc interceptor for list_workloads + + DEPRECATED. Please use the `post_list_workloads_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_list_workloads` interceptor runs + before the `post_list_workloads_with_metadata` interceptor. + """ + return response + + def post_list_workloads_with_metadata(self, response: environments.ListWorkloadsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListWorkloadsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_workloads + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_list_workloads_with_metadata` + interceptor in new development instead of the `post_list_workloads` interceptor. + When both interceptors are used, this `post_list_workloads_with_metadata` interceptor runs after the + `post_list_workloads` interceptor. The (possibly modified) response returned by + `post_list_workloads` will be passed to + `post_list_workloads_with_metadata`. + """ + return response, metadata + + def pre_load_snapshot(self, request: environments.LoadSnapshotRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.LoadSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for load_snapshot + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_load_snapshot(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for load_snapshot + + DEPRECATED. Please use the `post_load_snapshot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_load_snapshot` interceptor runs + before the `post_load_snapshot_with_metadata` interceptor. + """ + return response + + def post_load_snapshot_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for load_snapshot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_load_snapshot_with_metadata` + interceptor in new development instead of the `post_load_snapshot` interceptor. + When both interceptors are used, this `post_load_snapshot_with_metadata` interceptor runs after the + `post_load_snapshot` interceptor. The (possibly modified) response returned by + `post_load_snapshot` will be passed to + `post_load_snapshot_with_metadata`. + """ + return response, metadata + + def pre_poll_airflow_command(self, request: environments.PollAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.PollAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for poll_airflow_command + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_poll_airflow_command(self, response: environments.PollAirflowCommandResponse) -> environments.PollAirflowCommandResponse: + """Post-rpc interceptor for poll_airflow_command + + DEPRECATED. Please use the `post_poll_airflow_command_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_poll_airflow_command` interceptor runs + before the `post_poll_airflow_command_with_metadata` interceptor. + """ + return response + + def post_poll_airflow_command_with_metadata(self, response: environments.PollAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.PollAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for poll_airflow_command + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_poll_airflow_command_with_metadata` + interceptor in new development instead of the `post_poll_airflow_command` interceptor. + When both interceptors are used, this `post_poll_airflow_command_with_metadata` interceptor runs after the + `post_poll_airflow_command` interceptor. The (possibly modified) response returned by + `post_poll_airflow_command` will be passed to + `post_poll_airflow_command_with_metadata`. + """ + return response, metadata + + def pre_restart_web_server(self, request: environments.RestartWebServerRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.RestartWebServerRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for restart_web_server + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_restart_web_server(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for restart_web_server + + DEPRECATED. Please use the `post_restart_web_server_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_restart_web_server` interceptor runs + before the `post_restart_web_server_with_metadata` interceptor. + """ + return response + + def post_restart_web_server_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for restart_web_server + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_restart_web_server_with_metadata` + interceptor in new development instead of the `post_restart_web_server` interceptor. + When both interceptors are used, this `post_restart_web_server_with_metadata` interceptor runs after the + `post_restart_web_server` interceptor. The (possibly modified) response returned by + `post_restart_web_server` will be passed to + `post_restart_web_server_with_metadata`. + """ + return response, metadata + + def pre_save_snapshot(self, request: environments.SaveSnapshotRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.SaveSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for save_snapshot + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_save_snapshot(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for save_snapshot + + DEPRECATED. Please use the `post_save_snapshot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_save_snapshot` interceptor runs + before the `post_save_snapshot_with_metadata` interceptor. + """ + return response + + def post_save_snapshot_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for save_snapshot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_save_snapshot_with_metadata` + interceptor in new development instead of the `post_save_snapshot` interceptor. + When both interceptors are used, this `post_save_snapshot_with_metadata` interceptor runs after the + `post_save_snapshot` interceptor. The (possibly modified) response returned by + `post_save_snapshot` will be passed to + `post_save_snapshot_with_metadata`. + """ + return response, metadata + + def pre_stop_airflow_command(self, request: environments.StopAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.StopAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for stop_airflow_command + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_stop_airflow_command(self, response: environments.StopAirflowCommandResponse) -> environments.StopAirflowCommandResponse: + """Post-rpc interceptor for stop_airflow_command + + DEPRECATED. Please use the `post_stop_airflow_command_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_stop_airflow_command` interceptor runs + before the `post_stop_airflow_command_with_metadata` interceptor. + """ + return response + + def post_stop_airflow_command_with_metadata(self, response: environments.StopAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.StopAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for stop_airflow_command + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_stop_airflow_command_with_metadata` + interceptor in new development instead of the `post_stop_airflow_command` interceptor. + When both interceptors are used, this `post_stop_airflow_command_with_metadata` interceptor runs after the + `post_stop_airflow_command` interceptor. The (possibly modified) response returned by + `post_stop_airflow_command` will be passed to + `post_stop_airflow_command_with_metadata`. + """ + return response, metadata + + def pre_update_environment(self, request: environments.UpdateEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_environment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_update_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_environment + + DEPRECATED. Please use the `post_update_environment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_update_environment` interceptor runs + before the `post_update_environment_with_metadata` interceptor. + """ + return response + + def post_update_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_environment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_update_environment_with_metadata` + interceptor in new development instead of the `post_update_environment` interceptor. + When both interceptors are used, this `post_update_environment_with_metadata` interceptor runs after the + `post_update_environment` interceptor. The (possibly modified) response returned by + `post_update_environment` will be passed to + `post_update_environment_with_metadata`. + """ + return response, metadata + + def pre_update_user_workloads_config_map(self, request: environments.UpdateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_user_workloads_config_map + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_update_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: + """Post-rpc interceptor for update_user_workloads_config_map + + DEPRECATED. Please use the `post_update_user_workloads_config_map_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_update_user_workloads_config_map` interceptor runs + before the `post_update_user_workloads_config_map_with_metadata` interceptor. + """ + return response + + def post_update_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_user_workloads_config_map + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_update_user_workloads_config_map_with_metadata` + interceptor in new development instead of the `post_update_user_workloads_config_map` interceptor. + When both interceptors are used, this `post_update_user_workloads_config_map_with_metadata` interceptor runs after the + `post_update_user_workloads_config_map` interceptor. The (possibly modified) response returned by + `post_update_user_workloads_config_map` will be passed to + `post_update_user_workloads_config_map_with_metadata`. + """ + return response, metadata + + def pre_update_user_workloads_secret(self, request: environments.UpdateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_user_workloads_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the Environments server. + """ + return request, metadata + + def post_update_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: + """Post-rpc interceptor for update_user_workloads_secret + + DEPRECATED. Please use the `post_update_user_workloads_secret_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Environments server but before + it is returned to user code. This `post_update_user_workloads_secret` interceptor runs + before the `post_update_user_workloads_secret_with_metadata` interceptor. + """ + return response + + def post_update_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_user_workloads_secret + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Environments server but before it is returned to user code. + + We recommend only using this `post_update_user_workloads_secret_with_metadata` + interceptor in new development instead of the `post_update_user_workloads_secret` interceptor. + When both interceptors are used, this `post_update_user_workloads_secret_with_metadata` interceptor runs after the + `post_update_user_workloads_secret` interceptor. The (possibly modified) response returned by + `post_update_user_workloads_secret` will be passed to + `post_update_user_workloads_secret_with_metadata`. + """ + return response, metadata + + 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 Environments 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 Environments 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 Environments 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 Environments 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 Environments 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 Environments server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EnvironmentsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EnvironmentsRestInterceptor + + +class EnvironmentsRestTransport(_BaseEnvironmentsRestTransport): + """REST backend synchronous transport for Environments. + + Managed Apache Airflow Environments. + + 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 = 'composer.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[EnvironmentsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'composer.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 EnvironmentsRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CheckUpgrade(_BaseEnvironmentsRestTransport._BaseCheckUpgrade, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.CheckUpgrade") + + @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: environments.CheckUpgradeRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the check upgrade method over HTTP. + + Args: + request (~.environments.CheckUpgradeRequest): + The request object. Request to check whether image + upgrade will succeed. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_http_options() + + request, metadata = self._interceptor.pre_check_upgrade(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.CheckUpgrade", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "CheckUpgrade", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._CheckUpgrade._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_check_upgrade(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_check_upgrade_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.check_upgrade", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "CheckUpgrade", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateEnvironment(_BaseEnvironmentsRestTransport._BaseCreateEnvironment, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.CreateEnvironment") + + @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: environments.CreateEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create environment method over HTTP. + + Args: + request (~.environments.CreateEnvironmentRequest): + The request object. Create a new environment. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_http_options() + + request, metadata = self._interceptor.pre_create_environment(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.CreateEnvironment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "CreateEnvironment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._CreateEnvironment._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_environment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_environment_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_environment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "CreateEnvironment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.CreateUserWorkloadsConfigMap") + + @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: environments.CreateUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsConfigMap: + r"""Call the create user workloads + config map method over HTTP. + + Args: + request (~.environments.CreateUserWorkloadsConfigMapRequest): + The request object. Create user workloads ConfigMap + request. + retry (google.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: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_http_options() + + request, metadata = self._interceptor.pre_create_user_workloads_config_map(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.CreateUserWorkloadsConfigMap", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "CreateUserWorkloadsConfigMap", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._CreateUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() + pb_resp = environments.UserWorkloadsConfigMap.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_user_workloads_config_map(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_user_workloads_config_map_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_user_workloads_config_map", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "CreateUserWorkloadsConfigMap", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.CreateUserWorkloadsSecret") + + @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: environments.CreateUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsSecret: + r"""Call the create user workloads + secret method over HTTP. + + Args: + request (~.environments.CreateUserWorkloadsSecretRequest): + The request object. Create user workloads Secret request. + retry (google.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: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_http_options() + + request, metadata = self._interceptor.pre_create_user_workloads_secret(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.CreateUserWorkloadsSecret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "CreateUserWorkloadsSecret", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._CreateUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() + pb_resp = environments.UserWorkloadsSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_user_workloads_secret(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_user_workloads_secret_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_user_workloads_secret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "CreateUserWorkloadsSecret", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DatabaseFailover(_BaseEnvironmentsRestTransport._BaseDatabaseFailover, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.DatabaseFailover") + + @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: environments.DatabaseFailoverRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the database failover method over HTTP. + + Args: + request (~.environments.DatabaseFailoverRequest): + The request object. Request to trigger database failover + (only for highly resilient + environments). + retry (google.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 = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_http_options() + + request, metadata = self._interceptor.pre_database_failover(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.DatabaseFailover", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "DatabaseFailover", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._DatabaseFailover._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_database_failover(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_database_failover_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.database_failover", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "DatabaseFailover", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteEnvironment(_BaseEnvironmentsRestTransport._BaseDeleteEnvironment, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.DeleteEnvironment") + + @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: environments.DeleteEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete environment method over HTTP. + + Args: + request (~.environments.DeleteEnvironmentRequest): + The request object. Delete an environment. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_http_options() + + request, metadata = self._interceptor.pre_delete_environment(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.DeleteEnvironment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "DeleteEnvironment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._DeleteEnvironment._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_environment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_environment_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.delete_environment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "DeleteEnvironment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.DeleteUserWorkloadsConfigMap") + + @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: environments.DeleteUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete user workloads + config map method over HTTP. + + Args: + request (~.environments.DeleteUserWorkloadsConfigMapRequest): + The request object. Delete user workloads ConfigMap + request. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_http_options() + + request, metadata = self._interceptor.pre_delete_user_workloads_config_map(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.DeleteUserWorkloadsConfigMap", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "DeleteUserWorkloadsConfigMap", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._DeleteUserWorkloadsConfigMap._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) + + class _DeleteUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.DeleteUserWorkloadsSecret") + + @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: environments.DeleteUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete user workloads + secret method over HTTP. + + Args: + request (~.environments.DeleteUserWorkloadsSecretRequest): + The request object. Delete user workloads Secret request. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_http_options() + + request, metadata = self._interceptor.pre_delete_user_workloads_secret(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.DeleteUserWorkloadsSecret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "DeleteUserWorkloadsSecret", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._DeleteUserWorkloadsSecret._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) + + class _ExecuteAirflowCommand(_BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.ExecuteAirflowCommand") + + @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: environments.ExecuteAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.ExecuteAirflowCommandResponse: + r"""Call the execute airflow command method over HTTP. + + Args: + request (~.environments.ExecuteAirflowCommandRequest): + The request object. Execute Airflow Command request. + retry (google.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: + ~.environments.ExecuteAirflowCommandResponse: + Response to + ExecuteAirflowCommandRequest. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_http_options() + + request, metadata = self._interceptor.pre_execute_airflow_command(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ExecuteAirflowCommand", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ExecuteAirflowCommand", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._ExecuteAirflowCommand._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 = environments.ExecuteAirflowCommandResponse() + pb_resp = environments.ExecuteAirflowCommandResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_execute_airflow_command(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_execute_airflow_command_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.ExecuteAirflowCommandResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.execute_airflow_command", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ExecuteAirflowCommand", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchDatabaseProperties(_BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.FetchDatabaseProperties") + + @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: environments.FetchDatabasePropertiesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.FetchDatabasePropertiesResponse: + r"""Call the fetch database properties method over HTTP. + + Args: + request (~.environments.FetchDatabasePropertiesRequest): + The request object. Request to fetch properties of + environment's database. + retry (google.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: + ~.environments.FetchDatabasePropertiesResponse: + Response for + FetchDatabasePropertiesRequest. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_http_options() + + request, metadata = self._interceptor.pre_fetch_database_properties(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.FetchDatabaseProperties", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "FetchDatabaseProperties", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._FetchDatabaseProperties._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 = environments.FetchDatabasePropertiesResponse() + pb_resp = environments.FetchDatabasePropertiesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_database_properties(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_fetch_database_properties_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.FetchDatabasePropertiesResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.fetch_database_properties", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "FetchDatabaseProperties", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetEnvironment(_BaseEnvironmentsRestTransport._BaseGetEnvironment, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.GetEnvironment") + + @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: environments.GetEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.Environment: + r"""Call the get environment method over HTTP. + + Args: + request (~.environments.GetEnvironmentRequest): + The request object. Get an environment. + retry (google.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: + ~.environments.Environment: + An environment for running + orchestration tasks. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_http_options() + + request, metadata = self._interceptor.pre_get_environment(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseGetEnvironment._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.GetEnvironment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "GetEnvironment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._GetEnvironment._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 = environments.Environment() + pb_resp = environments.Environment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_environment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_environment_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.Environment.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_environment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "GetEnvironment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.GetUserWorkloadsConfigMap") + + @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: environments.GetUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsConfigMap: + r"""Call the get user workloads config + map method over HTTP. + + Args: + request (~.environments.GetUserWorkloadsConfigMapRequest): + The request object. Get user workloads ConfigMap request. + retry (google.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: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_http_options() + + request, metadata = self._interceptor.pre_get_user_workloads_config_map(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.GetUserWorkloadsConfigMap", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "GetUserWorkloadsConfigMap", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._GetUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() + pb_resp = environments.UserWorkloadsConfigMap.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_user_workloads_config_map(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_user_workloads_config_map_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_user_workloads_config_map", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "GetUserWorkloadsConfigMap", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.GetUserWorkloadsSecret") + + @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: environments.GetUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsSecret: + r"""Call the get user workloads secret method over HTTP. + + Args: + request (~.environments.GetUserWorkloadsSecretRequest): + The request object. Get user workloads Secret request. + retry (google.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: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_http_options() + + request, metadata = self._interceptor.pre_get_user_workloads_secret(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.GetUserWorkloadsSecret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "GetUserWorkloadsSecret", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._GetUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() + pb_resp = environments.UserWorkloadsSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_user_workloads_secret(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_user_workloads_secret_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_user_workloads_secret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "GetUserWorkloadsSecret", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListEnvironments(_BaseEnvironmentsRestTransport._BaseListEnvironments, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.ListEnvironments") + + @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: environments.ListEnvironmentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.ListEnvironmentsResponse: + r"""Call the list environments method over HTTP. + + Args: + request (~.environments.ListEnvironmentsRequest): + The request object. List environments in a project and + location. + retry (google.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: + ~.environments.ListEnvironmentsResponse: + The environments in a project and + location. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseListEnvironments._get_http_options() + + request, metadata = self._interceptor.pre_list_environments(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseListEnvironments._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseListEnvironments._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ListEnvironments", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ListEnvironments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._ListEnvironments._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 = environments.ListEnvironmentsResponse() + pb_resp = environments.ListEnvironmentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_environments(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_environments_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.ListEnvironmentsResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_environments", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ListEnvironments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListUserWorkloadsConfigMaps(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.ListUserWorkloadsConfigMaps") + + @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: environments.ListUserWorkloadsConfigMapsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.ListUserWorkloadsConfigMapsResponse: + r"""Call the list user workloads + config maps method over HTTP. + + Args: + request (~.environments.ListUserWorkloadsConfigMapsRequest): + The request object. List user workloads ConfigMaps + request. + retry (google.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: + ~.environments.ListUserWorkloadsConfigMapsResponse: + The user workloads ConfigMaps for a + given environment. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_http_options() + + request, metadata = self._interceptor.pre_list_user_workloads_config_maps(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ListUserWorkloadsConfigMaps", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ListUserWorkloadsConfigMaps", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._ListUserWorkloadsConfigMaps._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 = environments.ListUserWorkloadsConfigMapsResponse() + pb_resp = environments.ListUserWorkloadsConfigMapsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_user_workloads_config_maps(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_user_workloads_config_maps_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.ListUserWorkloadsConfigMapsResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_user_workloads_config_maps", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ListUserWorkloadsConfigMaps", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListUserWorkloadsSecrets(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.ListUserWorkloadsSecrets") + + @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: environments.ListUserWorkloadsSecretsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.ListUserWorkloadsSecretsResponse: + r"""Call the list user workloads + secrets method over HTTP. + + Args: + request (~.environments.ListUserWorkloadsSecretsRequest): + The request object. List user workloads Secrets request. + retry (google.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: + ~.environments.ListUserWorkloadsSecretsResponse: + The user workloads Secrets for a + given environment. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_http_options() + + request, metadata = self._interceptor.pre_list_user_workloads_secrets(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ListUserWorkloadsSecrets", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ListUserWorkloadsSecrets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._ListUserWorkloadsSecrets._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 = environments.ListUserWorkloadsSecretsResponse() + pb_resp = environments.ListUserWorkloadsSecretsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_user_workloads_secrets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_user_workloads_secrets_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.ListUserWorkloadsSecretsResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_user_workloads_secrets", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ListUserWorkloadsSecrets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListWorkloads(_BaseEnvironmentsRestTransport._BaseListWorkloads, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.ListWorkloads") + + @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: environments.ListWorkloadsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.ListWorkloadsResponse: + r"""Call the list workloads method over HTTP. + + Args: + request (~.environments.ListWorkloadsRequest): + The request object. Request for listing workloads in a + Cloud Composer environment. + retry (google.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: + ~.environments.ListWorkloadsResponse: + Response to ListWorkloadsRequest. + """ + + http_options = _BaseEnvironmentsRestTransport._BaseListWorkloads._get_http_options() + + request, metadata = self._interceptor.pre_list_workloads(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseListWorkloads._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseListWorkloads._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ListWorkloads", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ListWorkloads", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._ListWorkloads._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 = environments.ListWorkloadsResponse() + pb_resp = environments.ListWorkloadsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_workloads(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_workloads_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.ListWorkloadsResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_workloads", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ListWorkloads", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _LoadSnapshot(_BaseEnvironmentsRestTransport._BaseLoadSnapshot, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.LoadSnapshot") + + @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: environments.LoadSnapshotRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the load snapshot method over HTTP. + + Args: + request (~.environments.LoadSnapshotRequest): + The request object. Request to load a snapshot into a + Cloud Composer environment. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_http_options() + + request, metadata = self._interceptor.pre_load_snapshot(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.LoadSnapshot", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "LoadSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._LoadSnapshot._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_load_snapshot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_load_snapshot_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.load_snapshot", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "LoadSnapshot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _PollAirflowCommand(_BaseEnvironmentsRestTransport._BasePollAirflowCommand, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.PollAirflowCommand") + + @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: environments.PollAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.PollAirflowCommandResponse: + r"""Call the poll airflow command method over HTTP. + + Args: + request (~.environments.PollAirflowCommandRequest): + The request object. Poll Airflow Command request. + retry (google.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: + ~.environments.PollAirflowCommandResponse: + Response to + PollAirflowCommandRequest. + + """ + + http_options = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_http_options() + + request, metadata = self._interceptor.pre_poll_airflow_command(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.PollAirflowCommand", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "PollAirflowCommand", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._PollAirflowCommand._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 = environments.PollAirflowCommandResponse() + pb_resp = environments.PollAirflowCommandResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_poll_airflow_command(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_poll_airflow_command_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.PollAirflowCommandResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.poll_airflow_command", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "PollAirflowCommand", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RestartWebServer(_BaseEnvironmentsRestTransport._BaseRestartWebServer, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.RestartWebServer") + + @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: environments.RestartWebServerRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the restart web server method over HTTP. + + Args: + request (~.environments.RestartWebServerRequest): + The request object. Restart Airflow web server. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseRestartWebServer._get_http_options() + + request, metadata = self._interceptor.pre_restart_web_server(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseRestartWebServer._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseRestartWebServer._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseRestartWebServer._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.RestartWebServer", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "RestartWebServer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._RestartWebServer._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_restart_web_server(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_restart_web_server_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.restart_web_server", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "RestartWebServer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _SaveSnapshot(_BaseEnvironmentsRestTransport._BaseSaveSnapshot, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.SaveSnapshot") + + @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: environments.SaveSnapshotRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the save snapshot method over HTTP. + + Args: + request (~.environments.SaveSnapshotRequest): + The request object. Request to create a snapshot of a + Cloud Composer environment. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_http_options() + + request, metadata = self._interceptor.pre_save_snapshot(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.SaveSnapshot", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "SaveSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._SaveSnapshot._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_save_snapshot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_save_snapshot_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.save_snapshot", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "SaveSnapshot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _StopAirflowCommand(_BaseEnvironmentsRestTransport._BaseStopAirflowCommand, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.StopAirflowCommand") + + @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: environments.StopAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.StopAirflowCommandResponse: + r"""Call the stop airflow command method over HTTP. + + Args: + request (~.environments.StopAirflowCommandRequest): + The request object. Stop Airflow Command request. + retry (google.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: + ~.environments.StopAirflowCommandResponse: + Response to + StopAirflowCommandRequest. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_http_options() + + request, metadata = self._interceptor.pre_stop_airflow_command(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.StopAirflowCommand", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "StopAirflowCommand", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._StopAirflowCommand._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 = environments.StopAirflowCommandResponse() + pb_resp = environments.StopAirflowCommandResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_stop_airflow_command(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_stop_airflow_command_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.StopAirflowCommandResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.stop_airflow_command", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "StopAirflowCommand", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateEnvironment(_BaseEnvironmentsRestTransport._BaseUpdateEnvironment, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.UpdateEnvironment") + + @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: environments.UpdateEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update environment method over HTTP. + + Args: + request (~.environments.UpdateEnvironmentRequest): + The request object. Update an environment. + retry (google.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 = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_http_options() + + request, metadata = self._interceptor.pre_update_environment(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.UpdateEnvironment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "UpdateEnvironment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._UpdateEnvironment._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_environment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_environment_with_metadata(resp, response_metadata) + 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_environment", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "UpdateEnvironment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.UpdateUserWorkloadsConfigMap") + + @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: environments.UpdateUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsConfigMap: + r"""Call the update user workloads + config map method over HTTP. + + Args: + request (~.environments.UpdateUserWorkloadsConfigMapRequest): + The request object. Update user workloads ConfigMap + request. + retry (google.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: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_http_options() + + request, metadata = self._interceptor.pre_update_user_workloads_config_map(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.UpdateUserWorkloadsConfigMap", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "UpdateUserWorkloadsConfigMap", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._UpdateUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() + pb_resp = environments.UserWorkloadsConfigMap.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_user_workloads_config_map(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_user_workloads_config_map_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_user_workloads_config_map", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "UpdateUserWorkloadsConfigMap", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.UpdateUserWorkloadsSecret") + + @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: environments.UpdateUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> environments.UserWorkloadsSecret: + r"""Call the update user workloads + secret method over HTTP. + + Args: + request (~.environments.UpdateUserWorkloadsSecretRequest): + The request object. Update user workloads Secret request. + retry (google.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: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_http_options() + + request, metadata = self._interceptor.pre_update_user_workloads_secret(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_transcoded_request(http_options, request) + + body = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.UpdateUserWorkloadsSecret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "UpdateUserWorkloadsSecret", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._UpdateUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() + pb_resp = environments.UserWorkloadsSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_user_workloads_secret(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_user_workloads_secret_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_user_workloads_secret", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "UpdateUserWorkloadsSecret", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def check_upgrade(self) -> Callable[ + [environments.CheckUpgradeRequest], + 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._CheckUpgrade(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_environment(self) -> Callable[ + [environments.CreateEnvironmentRequest], + 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._CreateEnvironment(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_user_workloads_config_map(self) -> Callable[ + [environments.CreateUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + # 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._CreateUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_user_workloads_secret(self) -> Callable[ + [environments.CreateUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + # 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._CreateUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def database_failover(self) -> Callable[ + [environments.DatabaseFailoverRequest], + 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._DatabaseFailover(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_environment(self) -> Callable[ + [environments.DeleteEnvironmentRequest], + 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._DeleteEnvironment(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user_workloads_config_map(self) -> Callable[ + [environments.DeleteUserWorkloadsConfigMapRequest], + empty_pb2.Empty]: + # 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._DeleteUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user_workloads_secret(self) -> Callable[ + [environments.DeleteUserWorkloadsSecretRequest], + empty_pb2.Empty]: + # 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._DeleteUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def execute_airflow_command(self) -> Callable[ + [environments.ExecuteAirflowCommandRequest], + environments.ExecuteAirflowCommandResponse]: + # 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._ExecuteAirflowCommand(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_database_properties(self) -> Callable[ + [environments.FetchDatabasePropertiesRequest], + environments.FetchDatabasePropertiesResponse]: + # 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._FetchDatabaseProperties(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_environment(self) -> Callable[ + [environments.GetEnvironmentRequest], + environments.Environment]: + # 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._GetEnvironment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user_workloads_config_map(self) -> Callable[ + [environments.GetUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + # 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._GetUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user_workloads_secret(self) -> Callable[ + [environments.GetUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + # 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._GetUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_environments(self) -> Callable[ + [environments.ListEnvironmentsRequest], + environments.ListEnvironmentsResponse]: + # 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._ListEnvironments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_user_workloads_config_maps(self) -> Callable[ + [environments.ListUserWorkloadsConfigMapsRequest], + environments.ListUserWorkloadsConfigMapsResponse]: + # 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._ListUserWorkloadsConfigMaps(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_user_workloads_secrets(self) -> Callable[ + [environments.ListUserWorkloadsSecretsRequest], + environments.ListUserWorkloadsSecretsResponse]: + # 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._ListUserWorkloadsSecrets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workloads(self) -> Callable[ + [environments.ListWorkloadsRequest], + environments.ListWorkloadsResponse]: + # 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._ListWorkloads(self._session, self._host, self._interceptor) # type: ignore + + @property + def load_snapshot(self) -> Callable[ + [environments.LoadSnapshotRequest], + 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._LoadSnapshot(self._session, self._host, self._interceptor) # type: ignore + + @property + def poll_airflow_command(self) -> Callable[ + [environments.PollAirflowCommandRequest], + environments.PollAirflowCommandResponse]: + # 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._PollAirflowCommand(self._session, self._host, self._interceptor) # type: ignore + + @property + def restart_web_server(self) -> Callable[ + [environments.RestartWebServerRequest], + 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._RestartWebServer(self._session, self._host, self._interceptor) # type: ignore + + @property + def save_snapshot(self) -> Callable[ + [environments.SaveSnapshotRequest], + 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._SaveSnapshot(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_airflow_command(self) -> Callable[ + [environments.StopAirflowCommandRequest], + environments.StopAirflowCommandResponse]: + # 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._StopAirflowCommand(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_environment(self) -> Callable[ + [environments.UpdateEnvironmentRequest], + 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._UpdateEnvironment(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user_workloads_config_map(self) -> Callable[ + [environments.UpdateUserWorkloadsConfigMapRequest], + environments.UserWorkloadsConfigMap]: + # 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._UpdateUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user_workloads_secret(self) -> Callable[ + [environments.UpdateUserWorkloadsSecretRequest], + environments.UserWorkloadsSecret]: + # 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._UpdateUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseEnvironmentsRestTransport._BaseDeleteOperation, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._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(_BaseEnvironmentsRestTransport._BaseGetOperation, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.GetOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._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.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "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(_BaseEnvironmentsRestTransport._BaseListOperations, EnvironmentsRestStub): + def __hash__(self): + return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseEnvironmentsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ListOperations", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EnvironmentsRestTransport._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.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "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__=( + 'EnvironmentsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest_base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest_base.py new file mode 100644 index 000000000000..bf2121a26c83 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest_base.py @@ -0,0 +1,1121 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 EnvironmentsTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.orchestration.airflow.service_v1beta1.types import environments +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseEnvironmentsRestTransport(EnvironmentsTransport): + """Base REST backend transport for Environments. + + 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 = 'composer.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: 'composer.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 _BaseCheckUpgrade: + 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:checkUpgrade', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.CheckUpgradeRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateEnvironment: + 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': '/v1beta1/{parent=projects/*/locations/*}/environments', + 'body': 'environment', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.CreateEnvironmentRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateUserWorkloadsConfigMap: + 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': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', + 'body': 'user_workloads_config_map', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.CreateUserWorkloadsConfigMapRequest.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=True + ) + 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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateUserWorkloadsSecret: + 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': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', + 'body': 'user_workloads_secret', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.CreateUserWorkloadsSecretRequest.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=True + ) + 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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDatabaseFailover: + 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:databaseFailover', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.DatabaseFailoverRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteEnvironment: + 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': '/v1beta1/{name=projects/*/locations/*/environments/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.DeleteEnvironmentRequest.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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteUserWorkloadsConfigMap: + 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': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.DeleteUserWorkloadsConfigMapRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteUserWorkloadsSecret: + 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': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.DeleteUserWorkloadsSecretRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExecuteAirflowCommand: + 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:executeAirflowCommand', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.ExecuteAirflowCommandRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFetchDatabaseProperties: + 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:fetchDatabaseProperties', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.FetchDatabasePropertiesRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEnvironment: + 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': '/v1beta1/{name=projects/*/locations/*/environments/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.GetEnvironmentRequest.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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetUserWorkloadsConfigMap: + 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': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.GetUserWorkloadsConfigMapRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetUserWorkloadsSecret: + 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': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.GetUserWorkloadsSecretRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEnvironments: + 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': '/v1beta1/{parent=projects/*/locations/*}/environments', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.ListEnvironmentsRequest.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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUserWorkloadsConfigMaps: + 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': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.ListUserWorkloadsConfigMapsRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUserWorkloadsSecrets: + 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': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.ListUserWorkloadsSecretsRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListWorkloads: + 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': '/v1beta1/{parent=projects/*/locations/*/environments/*}/workloads', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.ListWorkloadsRequest.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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseListWorkloads._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseLoadSnapshot: + 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:loadSnapshot', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.LoadSnapshotRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePollAirflowCommand: + 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:pollAirflowCommand', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.PollAirflowCommandRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRestartWebServer: + 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': '/v1beta1/{name=projects/*/locations/*/environments/*}:restartWebServer', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.RestartWebServerRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSaveSnapshot: + 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:saveSnapshot', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.SaveSnapshotRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStopAirflowCommand: + 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:stopAirflowCommand', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.StopAirflowCommandRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEnvironment: + 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': '/v1beta1/{name=projects/*/locations/*/environments/*}', + 'body': 'environment', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.UpdateEnvironmentRequest.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=True + ) + 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=True, + )) + query_params.update(_BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateUserWorkloadsConfigMap: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'put', + 'uri': '/v1beta1/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', + 'body': 'user_workloads_config_map', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.UpdateUserWorkloadsConfigMapRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateUserWorkloadsSecret: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'put', + 'uri': '/v1beta1/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', + 'body': 'user_workloads_secret', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = environments.UpdateUserWorkloadsSecretRequest.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=True + ) + 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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + 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': '/v1beta1/{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': '/v1beta1/{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': '/v1beta1/{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__=( + '_BaseEnvironmentsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/__init__.py new file mode 100644 index 000000000000..cf004e25ae3f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/__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 ImageVersionsClient +from .async_client import ImageVersionsAsyncClient + +__all__ = ( + 'ImageVersionsClient', + 'ImageVersionsAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/async_client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/async_client.py new file mode 100644 index 000000000000..a6cf483863e5 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/async_client.py @@ -0,0 +1,536 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_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.cloud.orchestration.airflow.service_v1beta1.services.image_versions import pagers +from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import ImageVersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ImageVersionsGrpcAsyncIOTransport +from .client import ImageVersionsClient + +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 ImageVersionsAsyncClient: + """Readonly service to query available ImageVersions.""" + + _client: ImageVersionsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ImageVersionsClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod(ImageVersionsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ImageVersionsClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ImageVersionsClient.common_folder_path) + parse_common_folder_path = staticmethod(ImageVersionsClient.parse_common_folder_path) + common_organization_path = staticmethod(ImageVersionsClient.common_organization_path) + parse_common_organization_path = staticmethod(ImageVersionsClient.parse_common_organization_path) + common_project_path = staticmethod(ImageVersionsClient.common_project_path) + parse_common_project_path = staticmethod(ImageVersionsClient.parse_common_project_path) + common_location_path = staticmethod(ImageVersionsClient.common_location_path) + parse_common_location_path = staticmethod(ImageVersionsClient.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: + ImageVersionsAsyncClient: The constructed client. + """ + return ImageVersionsClient.from_service_account_info.__func__(ImageVersionsAsyncClient, 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: + ImageVersionsAsyncClient: The constructed client. + """ + return ImageVersionsClient.from_service_account_file.__func__(ImageVersionsAsyncClient, 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 ImageVersionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ImageVersionsTransport: + """Returns the transport used by the client instance. + + Returns: + ImageVersionsTransport: 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 = ImageVersionsClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ImageVersionsTransport, Callable[..., ImageVersionsTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the image versions 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,ImageVersionsTransport,Callable[..., ImageVersionsTransport]]]): + 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 ImageVersionsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ImageVersionsClient( + 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.orchestration.airflow.service_v1beta1.ImageVersionsAsyncClient`.", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "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.orchestration.airflow.service.v1beta1.ImageVersions", + "credentialsType": None, + } + ) + + async def list_image_versions(self, + request: Optional[Union[image_versions.ListImageVersionsRequest, 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.ListImageVersionsAsyncPager: + r"""List ImageVersions for provided 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.orchestration.airflow import service_v1beta1 + + async def sample_list_image_versions(): + # Create a client + client = service_v1beta1.ImageVersionsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ListImageVersionsRequest( + ) + + # Make the request + page_result = client.list_image_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest, dict]]): + The request object. List ImageVersions in a project and + location. + parent (:class:`str`): + List ImageVersions in the given + project and location, in the form: + "projects/{projectId}/locations/{locationId}" + + 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.orchestration.airflow.service_v1beta1.services.image_versions.pagers.ListImageVersionsAsyncPager: + The ImageVersions in a project and + location. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, image_versions.ListImageVersionsRequest): + request = image_versions.ListImageVersionsRequest(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_image_versions] + + # 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.ListImageVersionsAsyncPager( + method=rpc, + request=request, + response=response, + 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 __aenter__(self) -> "ImageVersionsAsyncClient": + 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__ = ( + "ImageVersionsAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py new file mode 100644 index 000000000000..d7e90206e07e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py @@ -0,0 +1,897 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +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.orchestration.airflow.service_v1beta1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, 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.cloud.orchestration.airflow.service_v1beta1.services.image_versions import pagers +from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import ImageVersionsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ImageVersionsGrpcTransport +from .transports.grpc_asyncio import ImageVersionsGrpcAsyncIOTransport +from .transports.rest import ImageVersionsRestTransport + + +class ImageVersionsClientMeta(type): + """Metaclass for the ImageVersions 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[ImageVersionsTransport]] + _transport_registry["grpc"] = ImageVersionsGrpcTransport + _transport_registry["grpc_asyncio"] = ImageVersionsGrpcAsyncIOTransport + _transport_registry["rest"] = ImageVersionsRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ImageVersionsTransport]: + """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 ImageVersionsClient(metaclass=ImageVersionsClientMeta): + """Readonly service to query available ImageVersions.""" + + @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 = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "composer.{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: + ImageVersionsClient: 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: + ImageVersionsClient: 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) -> ImageVersionsTransport: + """Returns the transport used by the client instance. + + Returns: + ImageVersionsTransport: The transport used by the client + instance. + """ + return self._transport + + @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 = ImageVersionsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ImageVersionsClient._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 = ImageVersionsClient._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 + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @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, ImageVersionsTransport, Callable[..., ImageVersionsTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the image versions 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,ImageVersionsTransport,Callable[..., ImageVersionsTransport]]]): + 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 ImageVersionsTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ImageVersionsClient._read_environment_variables() + self._client_cert_source = ImageVersionsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ImageVersionsClient._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, ImageVersionsTransport) + if transport_provided: + # transport is a ImageVersionsTransport 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(ImageVersionsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ImageVersionsClient._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[ImageVersionsTransport], Callable[..., ImageVersionsTransport]] = ( + ImageVersionsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ImageVersionsTransport], 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.orchestration.airflow.service_v1beta1.ImageVersionsClient`.", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "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.orchestration.airflow.service.v1beta1.ImageVersions", + "credentialsType": None, + } + ) + + def list_image_versions(self, + request: Optional[Union[image_versions.ListImageVersionsRequest, 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.ListImageVersionsPager: + r"""List ImageVersions for provided 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.orchestration.airflow import service_v1beta1 + + def sample_list_image_versions(): + # Create a client + client = service_v1beta1.ImageVersionsClient() + + # Initialize request argument(s) + request = service_v1beta1.ListImageVersionsRequest( + ) + + # Make the request + page_result = client.list_image_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest, dict]): + The request object. List ImageVersions in a project and + location. + parent (str): + List ImageVersions in the given + project and location, in the form: + "projects/{projectId}/locations/{locationId}" + + 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.orchestration.airflow.service_v1beta1.services.image_versions.pagers.ListImageVersionsPager: + The ImageVersions in a project and + location. + 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. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + 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, image_versions.ListImageVersionsRequest): + request = image_versions.ListImageVersionsRequest(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_image_versions] + + # 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.ListImageVersionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ImageVersionsClient": + 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() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + 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() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + 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,) + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ImageVersionsClient", +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/pagers.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/pagers.py new file mode 100644 index 000000000000..dc3ad7dbf978 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1.types import image_versions + + +class ListImageVersionsPager: + """A pager for iterating through ``list_image_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``image_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListImageVersions`` requests and continue to iterate + through the ``image_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse` + 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[..., image_versions.ListImageVersionsResponse], + request: image_versions.ListImageVersionsRequest, + response: image_versions.ListImageVersionsResponse, + *, + 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.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse): + 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 = image_versions.ListImageVersionsRequest(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[image_versions.ListImageVersionsResponse]: + 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[image_versions.ImageVersion]: + for page in self.pages: + yield from page.image_versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListImageVersionsAsyncPager: + """A pager for iterating through ``list_image_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``image_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListImageVersions`` requests and continue to iterate + through the ``image_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse` + 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[image_versions.ListImageVersionsResponse]], + request: image_versions.ListImageVersionsRequest, + response: image_versions.ListImageVersionsResponse, + *, + 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.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse): + 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 = image_versions.ListImageVersionsRequest(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[image_versions.ListImageVersionsResponse]: + 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[image_versions.ImageVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.image_versions: + 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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/README.rst new file mode 100644 index 000000000000..8d4dc0e29401 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ImageVersionsTransport` is the ABC for all transports. +- public child `ImageVersionsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ImageVersionsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseImageVersionsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ImageVersionsRestTransport` 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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/__init__.py new file mode 100644 index 000000000000..5ab47c371986 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/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 ImageVersionsTransport +from .grpc import ImageVersionsGrpcTransport +from .grpc_asyncio import ImageVersionsGrpcAsyncIOTransport +from .rest import ImageVersionsRestTransport +from .rest import ImageVersionsRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ImageVersionsTransport]] +_transport_registry['grpc'] = ImageVersionsGrpcTransport +_transport_registry['grpc_asyncio'] = ImageVersionsGrpcAsyncIOTransport +_transport_registry['rest'] = ImageVersionsRestTransport + +__all__ = ( + 'ImageVersionsTransport', + 'ImageVersionsGrpcTransport', + 'ImageVersionsGrpcAsyncIOTransport', + 'ImageVersionsRestTransport', + 'ImageVersionsRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/base.py new file mode 100644 index 000000000000..1c402b590d25 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/base.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ImageVersionsTransport(abc.ABC): + """Abstract transport class for ImageVersions.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'composer.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: 'composer.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_image_versions: gapic_v1.method.wrap_method( + self.list_image_versions, + 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 list_image_versions(self) -> Callable[ + [image_versions.ListImageVersionsRequest], + Union[ + image_versions.ListImageVersionsResponse, + Awaitable[image_versions.ListImageVersionsResponse] + ]]: + 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 delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ImageVersionsTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc.py new file mode 100644 index 000000000000..f4f9c729b101 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc.py @@ -0,0 +1,402 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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.orchestration.airflow.service_v1beta1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageVersionsTransport, 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.orchestration.airflow.service.v1beta1.ImageVersions", + "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.orchestration.airflow.service.v1beta1.ImageVersions", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ImageVersionsGrpcTransport(ImageVersionsTransport): + """gRPC backend transport for ImageVersions. + + Readonly service to query available ImageVersions. + + 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 = 'composer.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: 'composer.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] = {} + + 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 = 'composer.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 list_image_versions(self) -> Callable[ + [image_versions.ListImageVersionsRequest], + image_versions.ListImageVersionsResponse]: + r"""Return a callable for the list image versions method over gRPC. + + List ImageVersions for provided location. + + Returns: + Callable[[~.ListImageVersionsRequest], + ~.ListImageVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_image_versions' not in self._stubs: + self._stubs['list_image_versions'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.ImageVersions/ListImageVersions', + request_serializer=image_versions.ListImageVersionsRequest.serialize, + response_deserializer=image_versions.ListImageVersionsResponse.deserialize, + ) + return self._stubs['list_image_versions'] + + 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 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__ = ( + 'ImageVersionsGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc_asyncio.py new file mode 100644 index 000000000000..bf8fb63f15b4 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc_asyncio.py @@ -0,0 +1,437 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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.orchestration.airflow.service_v1beta1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import ImageVersionsGrpcTransport + +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.orchestration.airflow.service.v1beta1.ImageVersions", + "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.orchestration.airflow.service.v1beta1.ImageVersions", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ImageVersionsGrpcAsyncIOTransport(ImageVersionsTransport): + """gRPC AsyncIO backend transport for ImageVersions. + + Readonly service to query available ImageVersions. + + 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 = 'composer.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 = 'composer.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: 'composer.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] = {} + + 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 list_image_versions(self) -> Callable[ + [image_versions.ListImageVersionsRequest], + Awaitable[image_versions.ListImageVersionsResponse]]: + r"""Return a callable for the list image versions method over gRPC. + + List ImageVersions for provided location. + + Returns: + Callable[[~.ListImageVersionsRequest], + Awaitable[~.ListImageVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_image_versions' not in self._stubs: + self._stubs['list_image_versions'] = self._logged_channel.unary_unary( + '/google.cloud.orchestration.airflow.service.v1beta1.ImageVersions/ListImageVersions', + request_serializer=image_versions.ListImageVersionsRequest.serialize, + response_deserializer=image_versions.ListImageVersionsResponse.deserialize, + ) + return self._stubs['list_image_versions'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_image_versions: self._wrap_method( + self.list_image_versions, + 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 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__ = ( + 'ImageVersionsGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest.py new file mode 100644 index 000000000000..7da85d6557ac --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest.py @@ -0,0 +1,742 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseImageVersionsRestTransport +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 ImageVersionsRestInterceptor: + """Interceptor for ImageVersions. + + 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 ImageVersionsRestTransport. + + .. code-block:: python + class MyCustomImageVersionsInterceptor(ImageVersionsRestInterceptor): + def pre_list_image_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_image_versions(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ImageVersionsRestTransport(interceptor=MyCustomImageVersionsInterceptor()) + client = ImageVersionsClient(transport=transport) + + + """ + def pre_list_image_versions(self, request: image_versions.ListImageVersionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_versions.ListImageVersionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_image_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the ImageVersions server. + """ + return request, metadata + + def post_list_image_versions(self, response: image_versions.ListImageVersionsResponse) -> image_versions.ListImageVersionsResponse: + """Post-rpc interceptor for list_image_versions + + DEPRECATED. Please use the `post_list_image_versions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ImageVersions server but before + it is returned to user code. This `post_list_image_versions` interceptor runs + before the `post_list_image_versions_with_metadata` interceptor. + """ + return response + + def post_list_image_versions_with_metadata(self, response: image_versions.ListImageVersionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_versions.ListImageVersionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_image_versions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ImageVersions server but before it is returned to user code. + + We recommend only using this `post_list_image_versions_with_metadata` + interceptor in new development instead of the `post_list_image_versions` interceptor. + When both interceptors are used, this `post_list_image_versions_with_metadata` interceptor runs after the + `post_list_image_versions` interceptor. The (possibly modified) response returned by + `post_list_image_versions` will be passed to + `post_list_image_versions_with_metadata`. + """ + return response, metadata + + 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ImageVersionsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ImageVersionsRestInterceptor + + +class ImageVersionsRestTransport(_BaseImageVersionsRestTransport): + """REST backend synchronous transport for ImageVersions. + + Readonly service to query available ImageVersions. + + 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 = 'composer.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[ImageVersionsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'composer.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) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ImageVersionsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ListImageVersions(_BaseImageVersionsRestTransport._BaseListImageVersions, ImageVersionsRestStub): + def __hash__(self): + return hash("ImageVersionsRestTransport.ListImageVersions") + + @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: image_versions.ListImageVersionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> image_versions.ListImageVersionsResponse: + r"""Call the list image versions method over HTTP. + + Args: + request (~.image_versions.ListImageVersionsRequest): + The request object. List ImageVersions in a project and + location. + retry (google.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: + ~.image_versions.ListImageVersionsResponse: + The ImageVersions in a project and + location. + + """ + + http_options = _BaseImageVersionsRestTransport._BaseListImageVersions._get_http_options() + + request, metadata = self._interceptor.pre_list_image_versions(request, metadata) + transcoded_request = _BaseImageVersionsRestTransport._BaseListImageVersions._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseImageVersionsRestTransport._BaseListImageVersions._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.orchestration.airflow.service_v1beta1.ImageVersionsClient.ListImageVersions", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "rpcName": "ListImageVersions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ImageVersionsRestTransport._ListImageVersions._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 = image_versions.ListImageVersionsResponse() + pb_resp = image_versions.ListImageVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_image_versions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_image_versions_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = image_versions.ListImageVersionsResponse.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.orchestration.airflow.service_v1beta1.ImageVersionsClient.list_image_versions", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "rpcName": "ListImageVersions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def list_image_versions(self) -> Callable[ + [image_versions.ListImageVersionsRequest], + image_versions.ListImageVersionsResponse]: + # 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._ListImageVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseImageVersionsRestTransport._BaseDeleteOperation, ImageVersionsRestStub): + def __hash__(self): + return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseImageVersionsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1beta1.ImageVersionsClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ImageVersionsRestTransport._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(_BaseImageVersionsRestTransport._BaseGetOperation, ImageVersionsRestStub): + def __hash__(self): + return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseImageVersionsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1beta1.ImageVersionsClient.GetOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ImageVersionsRestTransport._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.orchestration.airflow.service_v1beta1.ImageVersionsAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "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(_BaseImageVersionsRestTransport._BaseListOperations, ImageVersionsRestStub): + def __hash__(self): + return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseImageVersionsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1beta1.ImageVersionsClient.ListOperations", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ImageVersionsRestTransport._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.orchestration.airflow.service_v1beta1.ImageVersionsAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "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__=( + 'ImageVersionsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest_base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest_base.py new file mode 100644 index 000000000000..e1d398c7a262 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest_base.py @@ -0,0 +1,196 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ImageVersionsTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseImageVersionsRestTransport(ImageVersionsTransport): + """Base REST backend transport for ImageVersions. + + 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 = 'composer.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: 'composer.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 _BaseListImageVersions: + 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': '/v1beta1/{parent=projects/*/locations/*}/imageVersions', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = image_versions.ListImageVersionsRequest.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=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + 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': '/v1beta1/{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': '/v1beta1/{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': '/v1beta1/{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__=( + '_BaseImageVersionsRestTransport', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py new file mode 100644 index 000000000000..408cabedddfa --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .environments import ( + AirflowMetadataRetentionPolicyConfig, + CheckUpgradeRequest, + CheckUpgradeResponse, + CloudDataLineageIntegration, + CreateEnvironmentRequest, + CreateUserWorkloadsConfigMapRequest, + CreateUserWorkloadsSecretRequest, + DatabaseConfig, + DatabaseFailoverRequest, + DatabaseFailoverResponse, + DataRetentionConfig, + DeleteEnvironmentRequest, + DeleteUserWorkloadsConfigMapRequest, + DeleteUserWorkloadsSecretRequest, + EncryptionConfig, + Environment, + EnvironmentConfig, + ExecuteAirflowCommandRequest, + ExecuteAirflowCommandResponse, + FetchDatabasePropertiesRequest, + FetchDatabasePropertiesResponse, + GetEnvironmentRequest, + GetUserWorkloadsConfigMapRequest, + GetUserWorkloadsSecretRequest, + IPAllocationPolicy, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + ListUserWorkloadsConfigMapsRequest, + ListUserWorkloadsConfigMapsResponse, + ListUserWorkloadsSecretsRequest, + ListUserWorkloadsSecretsResponse, + ListWorkloadsRequest, + ListWorkloadsResponse, + LoadSnapshotRequest, + LoadSnapshotResponse, + MaintenanceWindow, + MasterAuthorizedNetworksConfig, + NetworkingConfig, + NodeConfig, + PollAirflowCommandRequest, + PollAirflowCommandResponse, + PrivateClusterConfig, + PrivateEnvironmentConfig, + RecoveryConfig, + RestartWebServerRequest, + SaveSnapshotRequest, + SaveSnapshotResponse, + ScheduledSnapshotsConfig, + SoftwareConfig, + StopAirflowCommandRequest, + StopAirflowCommandResponse, + StorageConfig, + TaskLogsRetentionConfig, + UpdateEnvironmentRequest, + UpdateUserWorkloadsConfigMapRequest, + UpdateUserWorkloadsSecretRequest, + UserWorkloadsConfigMap, + UserWorkloadsSecret, + WebServerConfig, + WebServerNetworkAccessControl, + WorkloadsConfig, +) +from .image_versions import ( + ImageVersion, + ListImageVersionsRequest, + ListImageVersionsResponse, +) +from .operations import ( + OperationMetadata, +) + +__all__ = ( + 'AirflowMetadataRetentionPolicyConfig', + 'CheckUpgradeRequest', + 'CheckUpgradeResponse', + 'CloudDataLineageIntegration', + 'CreateEnvironmentRequest', + 'CreateUserWorkloadsConfigMapRequest', + 'CreateUserWorkloadsSecretRequest', + 'DatabaseConfig', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'DataRetentionConfig', + 'DeleteEnvironmentRequest', + 'DeleteUserWorkloadsConfigMapRequest', + 'DeleteUserWorkloadsSecretRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'GetEnvironmentRequest', + 'GetUserWorkloadsConfigMapRequest', + 'GetUserWorkloadsSecretRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'ListUserWorkloadsConfigMapsRequest', + 'ListUserWorkloadsConfigMapsResponse', + 'ListUserWorkloadsSecretsRequest', + 'ListUserWorkloadsSecretsResponse', + 'ListWorkloadsRequest', + 'ListWorkloadsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'RestartWebServerRequest', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'StorageConfig', + 'TaskLogsRetentionConfig', + 'UpdateEnvironmentRequest', + 'UpdateUserWorkloadsConfigMapRequest', + 'UpdateUserWorkloadsSecretRequest', + 'UserWorkloadsConfigMap', + 'UserWorkloadsSecret', + 'WebServerConfig', + 'WebServerNetworkAccessControl', + 'WorkloadsConfig', + 'ImageVersion', + 'ListImageVersionsRequest', + 'ListImageVersionsResponse', + 'OperationMetadata', +) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py new file mode 100644 index 000000000000..5ec9203b3c2e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py @@ -0,0 +1,3162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.orchestration.airflow.service.v1beta1', + manifest={ + 'CreateEnvironmentRequest', + 'GetEnvironmentRequest', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'DeleteEnvironmentRequest', + 'UpdateEnvironmentRequest', + 'RestartWebServerRequest', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'CreateUserWorkloadsSecretRequest', + 'GetUserWorkloadsSecretRequest', + 'ListUserWorkloadsSecretsRequest', + 'UpdateUserWorkloadsSecretRequest', + 'DeleteUserWorkloadsSecretRequest', + 'CreateUserWorkloadsConfigMapRequest', + 'GetUserWorkloadsConfigMapRequest', + 'ListUserWorkloadsConfigMapsRequest', + 'UpdateUserWorkloadsConfigMapRequest', + 'DeleteUserWorkloadsConfigMapRequest', + 'UserWorkloadsSecret', + 'ListUserWorkloadsSecretsResponse', + 'UserWorkloadsConfigMap', + 'ListUserWorkloadsConfigMapsResponse', + 'ListWorkloadsRequest', + 'ListWorkloadsResponse', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'EnvironmentConfig', + 'WebServerNetworkAccessControl', + 'SoftwareConfig', + 'IPAllocationPolicy', + 'NodeConfig', + 'PrivateClusterConfig', + 'NetworkingConfig', + 'PrivateEnvironmentConfig', + 'DatabaseConfig', + 'WebServerConfig', + 'EncryptionConfig', + 'MaintenanceWindow', + 'WorkloadsConfig', + 'DataRetentionConfig', + 'TaskLogsRetentionConfig', + 'AirflowMetadataRetentionPolicyConfig', + 'StorageConfig', + 'RecoveryConfig', + 'ScheduledSnapshotsConfig', + 'MasterAuthorizedNetworksConfig', + 'CloudDataLineageIntegration', + 'Environment', + 'CheckUpgradeRequest', + 'CheckUpgradeResponse', + }, +) + + +class CreateEnvironmentRequest(proto.Message): + r"""Create a new environment. + + Attributes: + parent (str): + The parent must be of the form + "projects/{projectId}/locations/{locationId}". + environment (google.cloud.orchestration.airflow.service_v1beta1.types.Environment): + The environment to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + environment: 'Environment' = proto.Field( + proto.MESSAGE, + number=2, + message='Environment', + ) + + +class GetEnvironmentRequest(proto.Message): + r"""Get an environment. + + Attributes: + name (str): + The resource name of the environment to get, + in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEnvironmentsRequest(proto.Message): + r"""List environments in a project and location. + + Attributes: + parent (str): + List environments in the given project and + location, in the form: + "projects/{projectId}/locations/{locationId}". + page_size (int): + The maximum number of environments to return. + page_token (str): + The next_page_token value returned from a previous List + 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 ListEnvironmentsResponse(proto.Message): + r"""The environments in a project and location. + + Attributes: + environments (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.Environment]): + The list of environments returned by a + ListEnvironmentsRequest. + next_page_token (str): + The page token used to query for the next + page if one exists. + """ + + @property + def raw_page(self): + return self + + environments: MutableSequence['Environment'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Environment', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteEnvironmentRequest(proto.Message): + r"""Delete an environment. + + Attributes: + name (str): + The environment to delete, in the form: + + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateEnvironmentRequest(proto.Message): + r"""Update an environment. + + Attributes: + name (str): + The relative resource name of the environment + to update, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + environment (google.cloud.orchestration.airflow.service_v1beta1.types.Environment): + A patch environment. Fields specified by the ``updateMask`` + will be copied from the patch environment into the + environment under update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A comma-separated list of paths, relative to + ``Environment``, of fields to update. For example, to set + the version of scikit-learn to install in the environment to + 0.19.0 and to remove an existing installation of argparse, + the ``updateMask`` parameter would include the following two + ``paths`` values: + "config.softwareConfig.pypiPackages.scikit-learn" and + "config.softwareConfig.pypiPackages.argparse". The included + patch environment would specify the scikit-learn version as + follows: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "scikit-learn":"==0.19.0" + } + } + } + } + + Note that in the above example, any existing PyPI packages + other than scikit-learn and argparse will be unaffected. + + Only one update type may be included in a single request's + ``updateMask``. For example, one cannot update both the PyPI + packages and labels in the same request. However, it is + possible to update multiple members of a map field + simultaneously in the same request. For example, to set the + labels "label1" and "label2" while clearing "label3" + (assuming it already exists), one can provide the paths + "labels.label1", "labels.label2", and "labels.label3" and + populate the patch environment as follows: + + :: + + { + "labels":{ + "label1":"new-label1-value" + "label2":"new-label2-value" + } + } + + Note that in the above example, any existing labels that are + not included in the ``updateMask`` will be unaffected. + + It is also possible to replace an entire map field by + providing the map field's path in the ``updateMask``. The + new value of the field will be that which is provided in the + patch environment. For example, to delete all pre-existing + user-specified PyPI packages and install botocore at version + 1.7.14, the ``updateMask`` would contain the path + "config.softwareConfig.pypiPackages", and the patch + environment would be the following: + + :: + + { + "config":{ + "softwareConfig":{ + "pypiPackages":{ + "botocore":"==1.7.14" + } + } + } + } + + **Note:** Only the following fields can be updated: + + - ``config.softwareConfig.pypiPackages`` + + - Replace all custom custom PyPI packages. If a + replacement package map is not included in + ``environment``, all custom PyPI packages are cleared. + It is an error to provide both this mask and a mask + specifying an individual package. + + - ``config.softwareConfig.pypiPackages.``\ packagename + + - Update the custom PyPI package *packagename*, + preserving other packages. To delete the package, + include it in ``updateMask``, and omit the mapping for + it in + ``environment.config.softwareConfig.pypiPackages``. It + is an error to provide both a mask of this form and + the ``config.softwareConfig.pypiPackages`` mask. + + - ``labels`` + + - Replace all environment labels. If a replacement + labels map is not included in ``environment``, all + labels are cleared. It is an error to provide both + this mask and a mask specifying one or more individual + labels. + + - ``labels.``\ labelName + + - Set the label named *labelName*, while preserving + other labels. To delete the label, include it in + ``updateMask`` and omit its mapping in + ``environment.labels``. It is an error to provide both + a mask of this form and the ``labels`` mask. + + - ``config.nodeCount`` + + - Horizontally scale the number of nodes in the + environment. An integer greater than or equal to 3 + must be provided in the ``config.nodeCount`` field. + Supported for Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerNetworkAccessControl`` + + - Replace the environment's current + WebServerNetworkAccessControl. + + - ``config.softwareConfig.airflowConfigOverrides`` + + - Replace all Apache Airflow config overrides. If a + replacement config overrides map is not included in + ``environment``, all config overrides are cleared. It + is an error to provide both this mask and a mask + specifying one or more individual config overrides. + + - ``config.softwareConfig.airflowConfigOverrides.``\ section-name + + - Override the Apache Airflow config property *name* in + the section named *section*, preserving other + properties. To delete the property override, include + it in ``updateMask`` and omit its mapping in + ``environment.config.softwareConfig.airflowConfigOverrides``. + It is an error to provide both a mask of this form and + the ``config.softwareConfig.airflowConfigOverrides`` + mask. + + - ``config.softwareConfig.envVariables`` + + - Replace all environment variables. If a replacement + environment variable map is not included in + ``environment``, all custom environment variables are + cleared. + + - ``config.softwareConfig.imageVersion`` + + - Upgrade the version of the environment in-place. Refer + to ``SoftwareConfig.image_version`` for information on + how to format the new image version. Additionally, the + new image version cannot effect a version downgrade, + and must match the current image version's Composer + and Airflow major versions. Consult the `Cloud + Composer version + list `__ + for valid values. + + - ``config.softwareConfig.schedulerCount`` + + - Horizontally scale the number of schedulers in + Airflow. A positive integer not greater than the + number of nodes must be provided in the + ``config.softwareConfig.schedulerCount`` field. + Supported for Cloud Composer environments in versions + composer-1.\ *.*-airflow-2.*.*. + + - ``config.softwareConfig.cloudDataLineageIntegration`` + + - Configuration for Cloud Data Lineage integration. + + - ``config.databaseConfig.machineType`` + + - Cloud SQL machine type used by Airflow database. It + has to be one of: db-n1-standard-2, db-n1-standard-4, + db-n1-standard-8 or db-n1-standard-16. Supported for + Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.webServerConfig.machineType`` + + - Machine type on which Airflow web server is running. + It has to be one of: composer-n1-webserver-2, + composer-n1-webserver-4 or composer-n1-webserver-8. + Supported for Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + - ``config.maintenanceWindow`` + + - Maintenance window during which Cloud Composer + components may be under maintenance. + + - ``config.workloadsConfig`` + + - The workloads configuration settings for the GKE + cluster associated with the Cloud Composer + environment. Supported for Cloud Composer environments + in versions composer-2.\ *.*-airflow-*.*.\* and newer. + + - ``config.environmentSize`` + + - The size of the Cloud Composer environment. Supported + for Cloud Composer environments in versions + composer-2.\ *.*-airflow-*.*.\* and newer. + """ + + name: str = proto.Field( + proto.STRING, + number=2, + ) + environment: 'Environment' = proto.Field( + proto.MESSAGE, + number=1, + message='Environment', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class RestartWebServerRequest(proto.Message): + r"""Restart Airflow web server. + + Attributes: + name (str): + The resource name of the environment to + restart the web server for, in the form: + + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ExecuteAirflowCommandRequest(proto.Message): + r"""Execute Airflow Command request. + + Attributes: + environment (str): + The resource name of the environment in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + command (str): + Airflow command. + subcommand (str): + Airflow subcommand. + parameters (MutableSequence[str]): + Parameters for the Airflow command/subcommand as an array of + arguments. It may contain positional arguments like + ``["my-dag-id"]``, key-value parameters like + ``["--foo=bar"]`` or ``["--foo","bar"]``, or other flags + like ``["-f"]``. + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + command: str = proto.Field( + proto.STRING, + number=2, + ) + subcommand: str = proto.Field( + proto.STRING, + number=3, + ) + parameters: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class ExecuteAirflowCommandResponse(proto.Message): + r"""Response to ExecuteAirflowCommandRequest. + + Attributes: + execution_id (str): + The unique ID of the command execution for + polling. + pod (str): + The name of the pod where the command is + executed. + pod_namespace (str): + The namespace of the pod where the command is + executed. + error (str): + Error message. Empty if there was no error. + """ + + execution_id: str = proto.Field( + proto.STRING, + number=1, + ) + pod: str = proto.Field( + proto.STRING, + number=2, + ) + pod_namespace: str = proto.Field( + proto.STRING, + number=3, + ) + error: str = proto.Field( + proto.STRING, + number=4, + ) + + +class StopAirflowCommandRequest(proto.Message): + r"""Stop Airflow Command request. + + Attributes: + environment (str): + The resource name of the environment in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + execution_id (str): + The unique ID of the command execution. + pod (str): + The name of the pod where the command is + executed. + pod_namespace (str): + The namespace of the pod where the command is + executed. + force (bool): + If true, the execution is terminated + forcefully (SIGKILL). If false, the execution is + stopped gracefully, giving it time for cleanup. + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + execution_id: str = proto.Field( + proto.STRING, + number=2, + ) + pod: str = proto.Field( + proto.STRING, + number=3, + ) + pod_namespace: str = proto.Field( + proto.STRING, + number=4, + ) + force: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class StopAirflowCommandResponse(proto.Message): + r"""Response to StopAirflowCommandRequest. + + Attributes: + is_done (bool): + Whether the execution is still running. + output (MutableSequence[str]): + Output message from stopping execution + request. + """ + + is_done: bool = proto.Field( + proto.BOOL, + number=1, + ) + output: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class PollAirflowCommandRequest(proto.Message): + r"""Poll Airflow Command request. + + Attributes: + environment (str): + The resource name of the environment in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + execution_id (str): + The unique ID of the command execution. + pod (str): + The name of the pod where the command is + executed. + pod_namespace (str): + The namespace of the pod where the command is + executed. + next_line_number (int): + Line number from which new logs should be + fetched. + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + execution_id: str = proto.Field( + proto.STRING, + number=2, + ) + pod: str = proto.Field( + proto.STRING, + number=3, + ) + pod_namespace: str = proto.Field( + proto.STRING, + number=4, + ) + next_line_number: int = proto.Field( + proto.INT32, + number=5, + ) + + +class PollAirflowCommandResponse(proto.Message): + r"""Response to PollAirflowCommandRequest. + + Attributes: + output (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse.Line]): + Output from the command execution. It may not + contain the full output and the caller may need + to poll for more lines. + output_end (bool): + Whether the command execution has finished + and there is no more output. + exit_info (google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse.ExitInfo): + The result exit status of the command. + """ + + class Line(proto.Message): + r"""Contains information about a single line from logs. + + Attributes: + line_number (int): + Number of the line. + content (str): + Text content of the log line. + """ + + line_number: int = proto.Field( + proto.INT32, + number=1, + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + + class ExitInfo(proto.Message): + r"""Information about how a command ended. + + Attributes: + exit_code (int): + The exit code from the command execution. + error (str): + Error message. Empty if there was no error. + """ + + exit_code: int = proto.Field( + proto.INT32, + number=1, + ) + error: str = proto.Field( + proto.STRING, + number=2, + ) + + output: MutableSequence[Line] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Line, + ) + output_end: bool = proto.Field( + proto.BOOL, + number=2, + ) + exit_info: ExitInfo = proto.Field( + proto.MESSAGE, + number=3, + message=ExitInfo, + ) + + +class CreateUserWorkloadsSecretRequest(proto.Message): + r"""Create user workloads Secret request. + + Attributes: + parent (str): + Required. The environment name to create a + Secret for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + user_workloads_secret (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret): + Required. User workloads Secret to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_workloads_secret: 'UserWorkloadsSecret' = proto.Field( + proto.MESSAGE, + number=2, + message='UserWorkloadsSecret', + ) + + +class GetUserWorkloadsSecretRequest(proto.Message): + r"""Get user workloads Secret request. + + Attributes: + name (str): + Required. The resource name of the Secret to + get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListUserWorkloadsSecretsRequest(proto.Message): + r"""List user workloads Secrets request. + + Attributes: + parent (str): + Required. List Secrets in the given + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + page_size (int): + Optional. The maximum number of Secrets to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List 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 UpdateUserWorkloadsSecretRequest(proto.Message): + r"""Update user workloads Secret request. + + Attributes: + user_workloads_secret (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret): + Optional. User workloads Secret to override. + """ + + user_workloads_secret: 'UserWorkloadsSecret' = proto.Field( + proto.MESSAGE, + number=1, + message='UserWorkloadsSecret', + ) + + +class DeleteUserWorkloadsSecretRequest(proto.Message): + r"""Delete user workloads Secret request. + + Attributes: + name (str): + Required. The Secret to delete, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateUserWorkloadsConfigMapRequest(proto.Message): + r"""Create user workloads ConfigMap request. + + Attributes: + parent (str): + Required. The environment name to create a + ConfigMap for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + user_workloads_config_map (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap): + Required. User workloads ConfigMap to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_workloads_config_map: 'UserWorkloadsConfigMap' = proto.Field( + proto.MESSAGE, + number=2, + message='UserWorkloadsConfigMap', + ) + + +class GetUserWorkloadsConfigMapRequest(proto.Message): + r"""Get user workloads ConfigMap request. + + Attributes: + name (str): + Required. The resource name of the ConfigMap + to get, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListUserWorkloadsConfigMapsRequest(proto.Message): + r"""List user workloads ConfigMaps request. + + Attributes: + parent (str): + Required. List ConfigMaps in the given + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + page_size (int): + Optional. The maximum number of ConfigMaps to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List 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 UpdateUserWorkloadsConfigMapRequest(proto.Message): + r"""Update user workloads ConfigMap request. + + Attributes: + user_workloads_config_map (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap): + Optional. User workloads ConfigMap to + override. + """ + + user_workloads_config_map: 'UserWorkloadsConfigMap' = proto.Field( + proto.MESSAGE, + number=1, + message='UserWorkloadsConfigMap', + ) + + +class DeleteUserWorkloadsConfigMapRequest(proto.Message): + r"""Delete user workloads ConfigMap request. + + Attributes: + name (str): + Required. The ConfigMap to delete, in the + form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UserWorkloadsSecret(proto.Message): + r"""User workloads Secret used by Airflow tasks that run with + Kubernetes executor or KubernetesPodOperator. + + Attributes: + name (str): + Identifier. The resource name of the Secret, + in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". + data (MutableMapping[str, str]): + Optional. The "data" field of Kubernetes + Secret, organized in key-value pairs, which can + contain sensitive values such as a password, a + token, or a key. The values for all keys have to + be base64-encoded strings. For details see: + https://kubernetes.io/docs/concepts/configuration/secret/ + + Example: + + { + "example": "ZXhhbXBsZV92YWx1ZQ==", + "another-example": + "YW5vdGhlcl9leGFtcGxlX3ZhbHVl" } + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +class ListUserWorkloadsSecretsResponse(proto.Message): + r"""The user workloads Secrets for a given environment. + + Attributes: + user_workloads_secrets (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret]): + The list of Secrets returned by a + ListUserWorkloadsSecretsRequest. + next_page_token (str): + The page token used to query for the next + page if one exists. + """ + + @property + def raw_page(self): + return self + + user_workloads_secrets: MutableSequence['UserWorkloadsSecret'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='UserWorkloadsSecret', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UserWorkloadsConfigMap(proto.Message): + r"""User workloads ConfigMap used by Airflow tasks that run with + Kubernetes executor or KubernetesPodOperator. + + Attributes: + name (str): + Identifier. The resource name of the + ConfigMap, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". + data (MutableMapping[str, str]): + Optional. The "data" field of Kubernetes ConfigMap, + organized in key-value pairs. For details see: + https://kubernetes.io/docs/concepts/configuration/configmap/ + + Example: + + { "example_key": "example_value", "another_key": + "another_value" } + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +class ListUserWorkloadsConfigMapsResponse(proto.Message): + r"""The user workloads ConfigMaps for a given environment. + + Attributes: + user_workloads_config_maps (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap]): + The list of ConfigMaps returned by a + ListUserWorkloadsConfigMapsRequest. + next_page_token (str): + The page token used to query for the next + page if one exists. + """ + + @property + def raw_page(self): + return self + + user_workloads_config_maps: MutableSequence['UserWorkloadsConfigMap'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='UserWorkloadsConfigMap', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListWorkloadsRequest(proto.Message): + r"""Request for listing workloads in a Cloud Composer + environment. + + Attributes: + parent (str): + Required. The environment name to get + workloads for, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + page_size (int): + Optional. The maximum number of environments + to return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The list filter. Currently only supports equality + on the type field. The value of a field specified in the + filter expression must be one ComposerWorkloadType enum + option. It's possible to get multiple types using "OR" + operator, e.g.: "type=SCHEDULER OR type=CELERY_WORKER". If + not specified, all items are returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListWorkloadsResponse(proto.Message): + r"""Response to ListWorkloadsRequest. + + Attributes: + workloads (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse.ComposerWorkload]): + The list of environment workloads. + next_page_token (str): + The page token used to query for the next + page if one exists. + """ + class ComposerWorkloadType(proto.Enum): + r"""Supported workload types. + + Values: + COMPOSER_WORKLOAD_TYPE_UNSPECIFIED (0): + Not able to determine the type of the + workload. + CELERY_WORKER (1): + Celery worker. + KUBERNETES_WORKER (2): + Kubernetes worker. + KUBERNETES_OPERATOR_POD (3): + Workload created by Kubernetes Pod Operator. + SCHEDULER (4): + Airflow scheduler. + DAG_PROCESSOR (5): + Airflow Dag processor. + TRIGGERER (6): + Airflow triggerer. + WEB_SERVER (7): + Airflow web server UI. + REDIS (8): + Redis. + """ + COMPOSER_WORKLOAD_TYPE_UNSPECIFIED = 0 + CELERY_WORKER = 1 + KUBERNETES_WORKER = 2 + KUBERNETES_OPERATOR_POD = 3 + SCHEDULER = 4 + DAG_PROCESSOR = 5 + TRIGGERER = 6 + WEB_SERVER = 7 + REDIS = 8 + + class ComposerWorkloadState(proto.Enum): + r"""Workload states. + + Values: + COMPOSER_WORKLOAD_STATE_UNSPECIFIED (0): + Not able to determine the status of the + workload. + PENDING (1): + Workload is in pending state and has not yet + started. + OK (2): + Workload is running fine. + WARNING (3): + Workload is running but there are some + non-critical problems. + ERROR (4): + Workload is not running due to an error. + SUCCEEDED (5): + Workload has finished execution with success. + FAILED (6): + Workload has finished execution with failure. + """ + COMPOSER_WORKLOAD_STATE_UNSPECIFIED = 0 + PENDING = 1 + OK = 2 + WARNING = 3 + ERROR = 4 + SUCCEEDED = 5 + FAILED = 6 + + class ComposerWorkload(proto.Message): + r"""Information about a single workload. + + Attributes: + name (str): + Name of a workload. + type_ (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse.ComposerWorkloadType): + Type of a workload. + status (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse.ComposerWorkloadStatus): + Output only. Status of a workload. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: 'ListWorkloadsResponse.ComposerWorkloadType' = proto.Field( + proto.ENUM, + number=2, + enum='ListWorkloadsResponse.ComposerWorkloadType', + ) + status: 'ListWorkloadsResponse.ComposerWorkloadStatus' = proto.Field( + proto.MESSAGE, + number=3, + message='ListWorkloadsResponse.ComposerWorkloadStatus', + ) + + class ComposerWorkloadStatus(proto.Message): + r"""Workload status. + + Attributes: + state (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse.ComposerWorkloadState): + Output only. Workload state. + status_message (str): + Output only. Text to provide more descriptive + status. + detailed_status_message (str): + Output only. Detailed message of the status. + """ + + state: 'ListWorkloadsResponse.ComposerWorkloadState' = proto.Field( + proto.ENUM, + number=1, + enum='ListWorkloadsResponse.ComposerWorkloadState', + ) + status_message: str = proto.Field( + proto.STRING, + number=2, + ) + detailed_status_message: str = proto.Field( + proto.STRING, + number=3, + ) + + @property + def raw_page(self): + return self + + workloads: MutableSequence[ComposerWorkload] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ComposerWorkload, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SaveSnapshotRequest(proto.Message): + r"""Request to create a snapshot of a Cloud Composer environment. + + Attributes: + environment (str): + The resource name of the source environment + in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + snapshot_location (str): + Location in a Cloud Storage where the + snapshot is going to be stored, e.g.: + "gs://my-bucket/snapshots". + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + snapshot_location: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SaveSnapshotResponse(proto.Message): + r"""Response to SaveSnapshotRequest. + + Attributes: + snapshot_path (str): + The fully-resolved Cloud Storage path of the created + snapshot, e.g.: + "gs://my-bucket/snapshots/project_location_environment_timestamp". + This field is populated only if the snapshot creation was + successful. + """ + + snapshot_path: str = proto.Field( + proto.STRING, + number=1, + ) + + +class LoadSnapshotRequest(proto.Message): + r"""Request to load a snapshot into a Cloud Composer environment. + + Attributes: + environment (str): + The resource name of the target environment + in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + snapshot_path (str): + A Cloud Storage path to a snapshot to load, e.g.: + "gs://my-bucket/snapshots/project_location_environment_timestamp". + skip_pypi_packages_installation (bool): + Whether or not to skip installing Pypi + packages when loading the environment's state. + skip_environment_variables_setting (bool): + Whether or not to skip setting environment + variables when loading the environment's state. + skip_airflow_overrides_setting (bool): + Whether or not to skip setting Airflow + overrides when loading the environment's state. + skip_gcs_data_copying (bool): + Whether or not to skip copying Cloud Storage + data when loading the environment's state. + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + snapshot_path: str = proto.Field( + proto.STRING, + number=2, + ) + skip_pypi_packages_installation: bool = proto.Field( + proto.BOOL, + number=3, + ) + skip_environment_variables_setting: bool = proto.Field( + proto.BOOL, + number=4, + ) + skip_airflow_overrides_setting: bool = proto.Field( + proto.BOOL, + number=5, + ) + skip_gcs_data_copying: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class LoadSnapshotResponse(proto.Message): + r"""Response to LoadSnapshotRequest. + """ + + +class DatabaseFailoverRequest(proto.Message): + r"""Request to trigger database failover (only for highly + resilient environments). + + Attributes: + environment (str): + Target environment: + + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DatabaseFailoverResponse(proto.Message): + r"""Response for DatabaseFailoverRequest. + """ + + +class FetchDatabasePropertiesRequest(proto.Message): + r"""Request to fetch properties of environment's database. + + Attributes: + environment (str): + Required. The resource name of the + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FetchDatabasePropertiesResponse(proto.Message): + r"""Response for FetchDatabasePropertiesRequest. + + Attributes: + primary_gce_zone (str): + The Compute Engine zone that the instance is + currently serving from. + secondary_gce_zone (str): + The Compute Engine zone that the failover + instance is currently serving from for a + regional Cloud SQL instance. + is_failover_replica_available (bool): + The availability status of the failover + replica. A false status indicates that the + failover replica is out of sync. The primary + instance can only fail over to the failover + replica when the status is true. + """ + + primary_gce_zone: str = proto.Field( + proto.STRING, + number=1, + ) + secondary_gce_zone: str = proto.Field( + proto.STRING, + number=2, + ) + is_failover_replica_available: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class EnvironmentConfig(proto.Message): + r"""Configuration information for an environment. + + Attributes: + gke_cluster (str): + Output only. The Kubernetes Engine cluster + used to run this environment. + dag_gcs_prefix (str): + Output only. The Cloud Storage prefix of the + DAGs for this environment. Although Cloud + Storage objects reside in a flat namespace, a + hierarchical file tree can be simulated using + "/"-delimited object name prefixes. DAG objects + for this environment reside in a simulated + directory with the given prefix. + node_count (int): + The number of nodes in the Kubernetes Engine cluster that + will be used to run this environment. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + software_config (google.cloud.orchestration.airflow.service_v1beta1.types.SoftwareConfig): + Optional. The configuration settings for + software inside the environment. + node_config (google.cloud.orchestration.airflow.service_v1beta1.types.NodeConfig): + Optional. The configuration used for the + Kubernetes Engine cluster. + private_environment_config (google.cloud.orchestration.airflow.service_v1beta1.types.PrivateEnvironmentConfig): + Optional. The configuration used for the + Private IP Cloud Composer environment. + web_server_network_access_control (google.cloud.orchestration.airflow.service_v1beta1.types.WebServerNetworkAccessControl): + Optional. The network-level access control + policy for the Airflow web server. If + unspecified, no network-level access + restrictions will be applied. + database_config (google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseConfig): + Optional. The configuration settings for + Cloud SQL instance used internally by Apache + Airflow software. + web_server_config (google.cloud.orchestration.airflow.service_v1beta1.types.WebServerConfig): + Optional. The configuration settings for the Airflow web + server App Engine instance. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + airflow_uri (str): + Output only. The URI of the Apache Airflow Web UI hosted + within this environment (see `Airflow web + interface `__). + airflow_byoid_uri (str): + Output only. The 'bring your own identity' variant of the + URI of the Apache Airflow Web UI hosted within this + environment, to be accessed with external identities using + workforce identity federation (see `Access environments with + workforce identity + federation `__). + encryption_config (google.cloud.orchestration.airflow.service_v1beta1.types.EncryptionConfig): + Optional. The encryption options for the + Cloud Composer environment and its dependencies. + Cannot be updated. + maintenance_window (google.cloud.orchestration.airflow.service_v1beta1.types.MaintenanceWindow): + Optional. The maintenance window is the + period when Cloud Composer components may + undergo maintenance. It is defined so that + maintenance is not executed during peak hours or + critical time periods. + + The system will not be under maintenance for + every occurrence of this window, but when + maintenance is planned, it will be scheduled + during the window. + + The maintenance window period must encompass at + least 12 hours per week. This may be split into + multiple chunks, each with a size of at least 4 + hours. + + If this value is omitted, the default value for + maintenance window is applied. By default, + maintenance windows are from 00:00:00 to + 04:00:00 (GMT) on Friday, Saturday, and Sunday + every week. + workloads_config (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig): + Optional. The workloads configuration settings for the GKE + cluster associated with the Cloud Composer environment. The + GKE cluster runs Airflow scheduler, web server and workers + workloads. + + This field is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + environment_size (google.cloud.orchestration.airflow.service_v1beta1.types.EnvironmentConfig.EnvironmentSize): + Optional. The size of the Cloud Composer environment. + + This field is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + master_authorized_networks_config (google.cloud.orchestration.airflow.service_v1beta1.types.MasterAuthorizedNetworksConfig): + Optional. The configuration options for GKE + cluster master authorized networks. By default + master authorized networks feature is: + + - in case of private environment: enabled with + no external networks allowlisted. + - in case of public environment: disabled. + recovery_config (google.cloud.orchestration.airflow.service_v1beta1.types.RecoveryConfig): + Optional. The Recovery settings configuration of an + environment. + + This field is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + data_retention_config (google.cloud.orchestration.airflow.service_v1beta1.types.DataRetentionConfig): + Optional. The configuration setting for + Airflow database data retention mechanism. + resilience_mode (google.cloud.orchestration.airflow.service_v1beta1.types.EnvironmentConfig.ResilienceMode): + Optional. Resilience mode of the Cloud Composer Environment. + + This field is supported for Cloud Composer environments in + versions composer-2.2.0-airflow-\ *.*.\* and newer. + """ + class EnvironmentSize(proto.Enum): + r"""The size of the Cloud Composer environment. + + Values: + ENVIRONMENT_SIZE_UNSPECIFIED (0): + The size of the environment is unspecified. + ENVIRONMENT_SIZE_SMALL (1): + The environment size is small. + ENVIRONMENT_SIZE_MEDIUM (2): + The environment size is medium. + ENVIRONMENT_SIZE_LARGE (3): + The environment size is large. + """ + ENVIRONMENT_SIZE_UNSPECIFIED = 0 + ENVIRONMENT_SIZE_SMALL = 1 + ENVIRONMENT_SIZE_MEDIUM = 2 + ENVIRONMENT_SIZE_LARGE = 3 + + class ResilienceMode(proto.Enum): + r"""Resilience mode of the Cloud Composer Environment. + + Values: + RESILIENCE_MODE_UNSPECIFIED (0): + Default mode doesn't change environment + parameters. + HIGH_RESILIENCE (1): + Enabled High Resilience mode, including Cloud + SQL HA. + """ + RESILIENCE_MODE_UNSPECIFIED = 0 + HIGH_RESILIENCE = 1 + + gke_cluster: str = proto.Field( + proto.STRING, + number=1, + ) + dag_gcs_prefix: str = proto.Field( + proto.STRING, + number=2, + ) + node_count: int = proto.Field( + proto.INT32, + number=3, + ) + software_config: 'SoftwareConfig' = proto.Field( + proto.MESSAGE, + number=4, + message='SoftwareConfig', + ) + node_config: 'NodeConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='NodeConfig', + ) + private_environment_config: 'PrivateEnvironmentConfig' = proto.Field( + proto.MESSAGE, + number=7, + message='PrivateEnvironmentConfig', + ) + web_server_network_access_control: 'WebServerNetworkAccessControl' = proto.Field( + proto.MESSAGE, + number=9, + message='WebServerNetworkAccessControl', + ) + database_config: 'DatabaseConfig' = proto.Field( + proto.MESSAGE, + number=10, + message='DatabaseConfig', + ) + web_server_config: 'WebServerConfig' = proto.Field( + proto.MESSAGE, + number=11, + message='WebServerConfig', + ) + airflow_uri: str = proto.Field( + proto.STRING, + number=6, + ) + airflow_byoid_uri: str = proto.Field( + proto.STRING, + number=21, + ) + encryption_config: 'EncryptionConfig' = proto.Field( + proto.MESSAGE, + number=12, + message='EncryptionConfig', + ) + maintenance_window: 'MaintenanceWindow' = proto.Field( + proto.MESSAGE, + number=13, + message='MaintenanceWindow', + ) + workloads_config: 'WorkloadsConfig' = proto.Field( + proto.MESSAGE, + number=15, + message='WorkloadsConfig', + ) + environment_size: EnvironmentSize = proto.Field( + proto.ENUM, + number=16, + enum=EnvironmentSize, + ) + master_authorized_networks_config: 'MasterAuthorizedNetworksConfig' = proto.Field( + proto.MESSAGE, + number=17, + message='MasterAuthorizedNetworksConfig', + ) + recovery_config: 'RecoveryConfig' = proto.Field( + proto.MESSAGE, + number=18, + message='RecoveryConfig', + ) + data_retention_config: 'DataRetentionConfig' = proto.Field( + proto.MESSAGE, + number=19, + message='DataRetentionConfig', + ) + resilience_mode: ResilienceMode = proto.Field( + proto.ENUM, + number=20, + enum=ResilienceMode, + ) + + +class WebServerNetworkAccessControl(proto.Message): + r"""Network-level access control policy for the Airflow web + server. + + Attributes: + allowed_ip_ranges (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.WebServerNetworkAccessControl.AllowedIpRange]): + A collection of allowed IP ranges with + descriptions. + """ + + class AllowedIpRange(proto.Message): + r"""Allowed IP range with user-provided description. + + Attributes: + value (str): + IP address or range, defined using CIDR notation, of + requests that this rule applies to. Examples: + ``192.168.1.1`` or ``192.168.0.0/16`` or ``2001:db8::/32`` + or ``2001:0db8:0000:0042:0000:8a2e:0370:7334``. + + IP range prefixes should be properly truncated. For example, + ``1.2.3.4/24`` should be truncated to ``1.2.3.0/24``. + Similarly, for IPv6, ``2001:db8::1/32`` should be truncated + to ``2001:db8::/32``. + description (str): + Optional. User-provided description. It must + contain at most 300 characters. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + + allowed_ip_ranges: MutableSequence[AllowedIpRange] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AllowedIpRange, + ) + + +class SoftwareConfig(proto.Message): + r"""Specifies the selection and configuration of software inside + the environment. + + Attributes: + image_version (str): + Optional. The version of the software running in the + environment. This encapsulates both the version of Cloud + Composer functionality and the version of Apache Airflow. It + must match the regular expression + ``composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)``. + When used as input, the server also checks if the provided + version is supported and denies the request for an + unsupported version. + + The Cloud Composer portion of the image version is a full + `semantic version `__, or an alias in + the form of major version number or ``latest``. When an + alias is provided, the server replaces it with the current + Cloud Composer version that satisfies the alias. + + The Apache Airflow portion of the image version is a full + semantic version that points to one of the supported Apache + Airflow versions, or an alias in the form of only major or + major.minor versions specified. When an alias is provided, + the server replaces it with the latest Apache Airflow + version that satisfies the alias and is supported in the + given Cloud Composer version. + + In all cases, the resolved image version is stored in the + same field. + + See also `version + list `__ + and `versioning + overview `__. + airflow_config_overrides (MutableMapping[str, str]): + Optional. Apache Airflow configuration properties to + override. + + Property keys contain the section and property names, + separated by a hyphen, for example + "core-dags_are_paused_at_creation". Section names must not + contain hyphens ("-"), opening square brackets ("["), or + closing square brackets ("]"). The property name must not be + empty and must not contain an equals sign ("=") or semicolon + (";"). Section and property names must not contain a period + ("."). Apache Airflow configuration property names must be + written in + `snake_case `__. + Property values can contain any character, and can be + written in any lower/upper case format. + + Certain Apache Airflow configuration property values are + `blocked `__, + and cannot be overridden. + pypi_packages (MutableMapping[str, str]): + Optional. Custom Python Package Index (PyPI) packages to be + installed in the environment. + + Keys refer to the lowercase package name such as "numpy" and + values are the lowercase extras and version specifier such + as "==1.12.0", "[devel,gcp_api]", or "[devel]>=1.8.2, + <1.9.2". To specify a package without pinning it to a + version specifier, use the empty string as the value. + env_variables (MutableMapping[str, str]): + Optional. Additional environment variables to provide to the + Apache Airflow scheduler, worker, and webserver processes. + + Environment variable names must match the regular expression + ``[a-zA-Z_][a-zA-Z0-9_]*``. They cannot specify Apache + Airflow software configuration overrides (they cannot match + the regular expression ``AIRFLOW__[A-Z0-9_]+__[A-Z0-9_]+``), + and they cannot match any of the following reserved names: + + - ``AIRFLOW_HOME`` + - ``C_FORCE_ROOT`` + - ``CONTAINER_NAME`` + - ``DAGS_FOLDER`` + - ``GCP_PROJECT`` + - ``GCS_BUCKET`` + - ``GKE_CLUSTER_NAME`` + - ``SQL_DATABASE`` + - ``SQL_INSTANCE`` + - ``SQL_PASSWORD`` + - ``SQL_PROJECT`` + - ``SQL_REGION`` + - ``SQL_USER`` + python_version (str): + Optional. The major version of Python used to run the Apache + Airflow scheduler, worker, and webserver processes. + + Can be set to '2' or '3'. If not specified, the default is + '3'. Cannot be updated. + + This field is only supported for Cloud Composer environments + in versions composer-1.\ *.*-airflow-*.*.*. Environments in + newer versions always use Python major version 3. + scheduler_count (int): + Optional. The number of schedulers for Airflow. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-2.*.*. + cloud_data_lineage_integration (google.cloud.orchestration.airflow.service_v1beta1.types.CloudDataLineageIntegration): + Optional. The configuration for Cloud Data + Lineage integration. + web_server_plugins_mode (google.cloud.orchestration.airflow.service_v1beta1.types.SoftwareConfig.WebServerPluginsMode): + Optional. Whether or not the web server uses custom plugins. + If unspecified, the field defaults to ``PLUGINS_ENABLED``. + + This field is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + """ + class WebServerPluginsMode(proto.Enum): + r"""Web server plugins mode of the Cloud Composer environment. + + Values: + WEB_SERVER_PLUGINS_MODE_UNSPECIFIED (0): + Default mode. + PLUGINS_DISABLED (1): + Web server plugins are not supported. + PLUGINS_ENABLED (2): + Web server plugins are supported. + """ + WEB_SERVER_PLUGINS_MODE_UNSPECIFIED = 0 + PLUGINS_DISABLED = 1 + PLUGINS_ENABLED = 2 + + image_version: str = proto.Field( + proto.STRING, + number=1, + ) + airflow_config_overrides: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + pypi_packages: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + env_variables: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + python_version: str = proto.Field( + proto.STRING, + number=6, + ) + scheduler_count: int = proto.Field( + proto.INT32, + number=7, + ) + cloud_data_lineage_integration: 'CloudDataLineageIntegration' = proto.Field( + proto.MESSAGE, + number=8, + message='CloudDataLineageIntegration', + ) + web_server_plugins_mode: WebServerPluginsMode = proto.Field( + proto.ENUM, + number=10, + enum=WebServerPluginsMode, + ) + + +class IPAllocationPolicy(proto.Message): + r"""Configuration for controlling how IPs are allocated in the + GKE cluster. + + Attributes: + use_ip_aliases (bool): + Optional. Whether or not to enable Alias IPs in the GKE + cluster. If ``true``, a VPC-native cluster is created. + + This field is only supported for Cloud Composer environments + in versions composer-1.\ *.*-airflow-*.*.*. Environments in + newer versions always use VPC-native GKE clusters. + cluster_secondary_range_name (str): + Optional. The name of the cluster's secondary range used to + allocate IP addresses to pods. Specify either + ``cluster_secondary_range_name`` or + ``cluster_ipv4_cidr_block`` but not both. + + For Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*, this field is applicable + only when ``use_ip_aliases`` is true. + services_secondary_range_name (str): + Optional. The name of the services' secondary range used to + allocate IP addresses to the cluster. Specify either + ``services_secondary_range_name`` or + ``services_ipv4_cidr_block`` but not both. + + For Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*, this field is applicable + only when ``use_ip_aliases`` is true. + cluster_ipv4_cidr_block (str): + Optional. The IP address range used to allocate IP addresses + to pods in the cluster. + + For Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*, this field is applicable + only when ``use_ip_aliases`` is true. + + Set to blank to have GKE choose a range with the default + size. + + Set to /netmask (e.g. ``/14``) to have GKE choose a range + with a specific netmask. + + Set to a + `CIDR `__ + notation (e.g. ``10.96.0.0/14``) from the RFC-1918 private + networks (e.g. ``10.0.0.0/8``, ``172.16.0.0/12``, + ``192.168.0.0/16``) to pick a specific range to use. Specify + ``cluster_secondary_range_name`` or + ``cluster_ipv4_cidr_block`` but not both. + services_ipv4_cidr_block (str): + Optional. The IP address range of the services IP addresses + in this cluster. + + For Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*, this field is applicable + only when ``use_ip_aliases`` is true. + + Set to blank to have GKE choose a range with the default + size. + + Set to /netmask (e.g. ``/14``) to have GKE choose a range + with a specific netmask. + + Set to a + `CIDR `__ + notation (e.g. ``10.96.0.0/14``) from the RFC-1918 private + networks (e.g. ``10.0.0.0/8``, ``172.16.0.0/12``, + ``192.168.0.0/16``) to pick a specific range to use. Specify + ``services_secondary_range_name`` or + ``services_ipv4_cidr_block`` but not both. + """ + + use_ip_aliases: bool = proto.Field( + proto.BOOL, + number=1, + ) + cluster_secondary_range_name: str = proto.Field( + proto.STRING, + number=2, + ) + services_secondary_range_name: str = proto.Field( + proto.STRING, + number=3, + ) + cluster_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=4, + ) + services_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=5, + ) + + +class NodeConfig(proto.Message): + r"""The configuration information for the Kubernetes Engine nodes + running the Apache Airflow software. + + Attributes: + location (str): + Optional. The Compute Engine + `zone `__ in which to deploy + the VMs used to run the Apache Airflow software, specified + as a `relative resource + name `__. + For example: "projects/{projectId}/zones/{zoneId}". + + This ``location`` must belong to the enclosing environment's + project and location. If both this field and + ``nodeConfig.machineType`` are specified, + ``nodeConfig.machineType`` must belong to this ``location``; + if both are unspecified, the service will pick a zone in the + Compute Engine region corresponding to the Cloud Composer + location, and propagate that choice to both fields. If only + one field (``location`` or ``nodeConfig.machineType``) is + specified, the location information from the specified field + will be propagated to the unspecified field. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + machine_type (str): + Optional. The Compute Engine `machine + type `__ used for cluster + instances, specified as a `relative resource + name `__. + For example: + "projects/{projectId}/zones/{zoneId}/machineTypes/{machineTypeId}". + + The ``machineType`` must belong to the enclosing + environment's project and location. If both this field and + ``nodeConfig.location`` are specified, this ``machineType`` + must belong to the ``nodeConfig.location``; if both are + unspecified, the service will pick a zone in the Compute + Engine region corresponding to the Cloud Composer location, + and propagate that choice to both fields. If exactly one of + this field and ``nodeConfig.location`` is specified, the + location information from the specified field will be + propagated to the unspecified field. + + The ``machineTypeId`` must not be a `shared-core machine + type `__. + + If this field is unspecified, the ``machineTypeId`` defaults + to "n1-standard-1". + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + network (str): + Optional. The Compute Engine network to be used for machine + communications, specified as a `relative resource + name `__. + For example: + "projects/{projectId}/global/networks/{networkId}". + + If unspecified, the default network in the environment's + project is used. If a `Custom Subnet + Network `__ is + provided, ``nodeConfig.subnetwork`` must also be provided. + For `Shared VPC `__ subnetwork + requirements, see ``nodeConfig.subnetwork``. + subnetwork (str): + Optional. The Compute Engine subnetwork to be used for + machine communications, specified as a `relative resource + name `__. + For example: + "projects/{projectId}/regions/{regionId}/subnetworks/{subnetworkId}" + + If a subnetwork is provided, ``nodeConfig.network`` must + also be provided, and the subnetwork must belong to the + enclosing environment's project and location. + disk_size_gb (int): + Optional. The disk size in GB used for node VMs. Minimum + size is 30GB. If unspecified, defaults to 100GB. Cannot be + updated. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + oauth_scopes (MutableSequence[str]): + Optional. The set of Google API scopes to be made available + on all node VMs. If ``oauth_scopes`` is empty, defaults to + ["https://www.googleapis.com/auth/cloud-platform"]. Cannot + be updated. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + service_account (str): + Optional. The Google Cloud Platform Service + Account to be used by the workloads. If a + service account is not specified, the "default" + Compute Engine service account is used. Cannot + be updated. + tags (MutableSequence[str]): + Optional. The list of instance tags applied to all node VMs. + Tags are used to identify valid sources or targets for + network firewalls. Each tag within the list must comply with + `RFC1035 `__. Cannot + be updated. + ip_allocation_policy (google.cloud.orchestration.airflow.service_v1beta1.types.IPAllocationPolicy): + Optional. The IPAllocationPolicy fields for + the GKE cluster. + max_pods_per_node (int): + Optional. The maximum number of pods per node in the Cloud + Composer GKE cluster. The value must be between 8 and 110 + and it can be set only if the environment is VPC-native. The + default value is 32. Values of this field will be propagated + both to the ``default-pool`` node pool of the newly created + GKE cluster, and to the default "Maximum Pods per Node" + value which is used for newly created node pools if their + value is not explicitly set during node pool creation. For + more information, see [Optimizing IP address allocation] + (https://cloud.google.com/kubernetes-engine/docs/how-to/flexible-pod-cidr). + Cannot be updated. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + enable_ip_masq_agent (bool): + Optional. Deploys 'ip-masq-agent' daemon set + in the GKE cluster and defines + nonMasqueradeCIDRs equals to pod IP range so IP + masquerading is used for all destination + addresses, except between pods traffic. + + See: + + https://cloud.google.com/kubernetes-engine/docs/how-to/ip-masquerade-agent + composer_network_attachment (str): + Optional. Network Attachment that Cloud Composer environment + is connected to, which provides connectivity with a user's + VPC network. Takes precedence over network and subnetwork + settings. If not provided, but network and subnetwork are + defined during environment, it will be provisioned. If not + provided and network and subnetwork are also empty, then + connectivity to user's VPC network is disabled. Network + attachment must be provided in format + projects/{project}/regions/{region}/networkAttachments/{networkAttachment}. + + This field is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + composer_internal_ipv4_cidr_block (str): + Optional. The IP range in CIDR notation to use internally by + Cloud Composer. IP addresses are not reserved - and the same + range can be used by multiple Cloud Composer environments. + In case of overlap, IPs from this range will not be + accessible in the user's VPC network. Cannot be updated. If + not specified, the default value of '100.64.128.0/20' is + used. + + This field is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + """ + + location: str = proto.Field( + proto.STRING, + number=1, + ) + machine_type: str = proto.Field( + proto.STRING, + number=2, + ) + network: str = proto.Field( + proto.STRING, + number=3, + ) + subnetwork: str = proto.Field( + proto.STRING, + number=4, + ) + disk_size_gb: int = proto.Field( + proto.INT32, + number=5, + ) + oauth_scopes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + service_account: str = proto.Field( + proto.STRING, + number=7, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + ip_allocation_policy: 'IPAllocationPolicy' = proto.Field( + proto.MESSAGE, + number=9, + message='IPAllocationPolicy', + ) + max_pods_per_node: int = proto.Field( + proto.INT32, + number=10, + ) + enable_ip_masq_agent: bool = proto.Field( + proto.BOOL, + number=11, + ) + composer_network_attachment: str = proto.Field( + proto.STRING, + number=12, + ) + composer_internal_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=13, + ) + + +class PrivateClusterConfig(proto.Message): + r"""Configuration options for the private GKE cluster in a Cloud + Composer environment. + + Attributes: + enable_private_endpoint (bool): + Optional. If ``true``, access to the public endpoint of the + GKE cluster is denied. + master_ipv4_cidr_block (str): + Optional. The CIDR block from which IPv4 + range for GKE master will be reserved. If left + blank, the default value of '172.16.0.0/23' is + used. + master_ipv4_reserved_range (str): + Output only. The IP range in CIDR notation to + use for the hosted master network. This range is + used for assigning internal IP addresses to the + cluster master or set of masters and to the + internal load balancer virtual IP. This range + must not overlap with any other ranges in use + within the cluster's network. + """ + + enable_private_endpoint: bool = proto.Field( + proto.BOOL, + number=1, + ) + master_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=2, + ) + master_ipv4_reserved_range: str = proto.Field( + proto.STRING, + number=3, + ) + + +class NetworkingConfig(proto.Message): + r"""Configuration options for networking connections in the + Composer 2 environment. + + Attributes: + connection_type (google.cloud.orchestration.airflow.service_v1beta1.types.NetworkingConfig.ConnectionType): + Optional. Indicates the user requested + specifc connection type between Tenant and + Customer projects. You cannot set networking + connection type in public IP environment. + """ + class ConnectionType(proto.Enum): + r"""Represents connection type between Composer environment in + Customer Project and the corresponding Tenant project, from a + predefined list of available connection modes. + + Values: + CONNECTION_TYPE_UNSPECIFIED (0): + No specific connection type was requested, so + the environment uses the default value + corresponding to the rest of its configuration. + VPC_PEERING (1): + Requests the use of VPC peerings for + connecting the Customer and Tenant projects. + PRIVATE_SERVICE_CONNECT (2): + Requests the use of Private Service Connect + for connecting the Customer and Tenant projects. + """ + CONNECTION_TYPE_UNSPECIFIED = 0 + VPC_PEERING = 1 + PRIVATE_SERVICE_CONNECT = 2 + + connection_type: ConnectionType = proto.Field( + proto.ENUM, + number=1, + enum=ConnectionType, + ) + + +class PrivateEnvironmentConfig(proto.Message): + r"""The configuration information for configuring a Private IP + Cloud Composer environment. + + Attributes: + enable_private_environment (bool): + Optional. If ``true``, a Private IP Cloud Composer + environment is created. If this field is set to true, + ``IPAllocationPolicy.use_ip_aliases`` must be set to true + for Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + enable_private_builds_only (bool): + Optional. If ``true``, builds performed during operations + that install Python packages have only private connectivity + to Google services (including Artifact Registry) and VPC + network (if either ``NodeConfig.network`` and + ``NodeConfig.subnetwork`` fields or + ``NodeConfig.composer_network_attachment`` field are + specified). If ``false``, the builds also have access to the + internet. + + This field is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + private_cluster_config (google.cloud.orchestration.airflow.service_v1beta1.types.PrivateClusterConfig): + Optional. Configuration for the private GKE + cluster for a Private IP Cloud Composer + environment. + web_server_ipv4_cidr_block (str): + Optional. The CIDR block from which IP range for web server + will be reserved. Needs to be disjoint from + private_cluster_config.master_ipv4_cidr_block and + cloud_sql_ipv4_cidr_block. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + cloud_sql_ipv4_cidr_block (str): + Optional. The CIDR block from which IP range in tenant + project will be reserved for Cloud SQL. Needs to be disjoint + from web_server_ipv4_cidr_block + web_server_ipv4_reserved_range (str): + Output only. The IP range reserved for the tenant project's + App Engine VMs. + + This field is supported for Cloud Composer environments in + versions composer-1.\ *.*-airflow-*.*.*. + cloud_composer_network_ipv4_cidr_block (str): + Optional. The CIDR block from which IP range for Cloud + Composer Network in tenant project will be reserved. Needs + to be disjoint from + private_cluster_config.master_ipv4_cidr_block and + cloud_sql_ipv4_cidr_block. + + This field is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + cloud_composer_network_ipv4_reserved_range (str): + Output only. The IP range reserved for the tenant project's + Cloud Composer network. + + This field is supported for Cloud Composer environments in + versions composer-2.\ *.*-airflow-*.*.\* and newer. + enable_privately_used_public_ips (bool): + Optional. When enabled, IPs from public (non-RFC1918) ranges + can be used for + ``IPAllocationPolicy.cluster_ipv4_cidr_block`` and + ``IPAllocationPolicy.service_ipv4_cidr_block``. + cloud_composer_connection_subnetwork (str): + Optional. When specified, the environment + will use Private Service Connect instead of VPC + peerings to connect to Cloud SQL in the Tenant + Project, and the PSC endpoint in the Customer + Project will use an IP address from this + subnetwork. + networking_config (google.cloud.orchestration.airflow.service_v1beta1.types.NetworkingConfig): + Optional. Configuration for the network + connections configuration in the environment. + """ + + enable_private_environment: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_private_builds_only: bool = proto.Field( + proto.BOOL, + number=11, + ) + private_cluster_config: 'PrivateClusterConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='PrivateClusterConfig', + ) + web_server_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=3, + ) + cloud_sql_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=4, + ) + web_server_ipv4_reserved_range: str = proto.Field( + proto.STRING, + number=5, + ) + cloud_composer_network_ipv4_cidr_block: str = proto.Field( + proto.STRING, + number=7, + ) + cloud_composer_network_ipv4_reserved_range: str = proto.Field( + proto.STRING, + number=8, + ) + enable_privately_used_public_ips: bool = proto.Field( + proto.BOOL, + number=6, + ) + cloud_composer_connection_subnetwork: str = proto.Field( + proto.STRING, + number=9, + ) + networking_config: 'NetworkingConfig' = proto.Field( + proto.MESSAGE, + number=10, + message='NetworkingConfig', + ) + + +class DatabaseConfig(proto.Message): + r"""The configuration of Cloud SQL instance that is used by the + Apache Airflow software. + + Attributes: + machine_type (str): + Optional. Cloud SQL machine type used by Airflow database. + It has to be one of: db-n1-standard-2, db-n1-standard-4, + db-n1-standard-8 or db-n1-standard-16. If not specified, + db-n1-standard-2 will be used. Supported for Cloud Composer + environments in versions composer-1.\ *.*-airflow-*.*.*. + zone (str): + Optional. The Compute Engine zone where the Airflow database + is created. If zone is provided, it must be in the region + selected for the environment. If zone is not provided, a + zone is automatically selected. The zone can only be set + during environment creation. Supported for Cloud Composer + environments in versions composer-2.\ *.*-airflow-*.*.*. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + zone: str = proto.Field( + proto.STRING, + number=2, + ) + + +class WebServerConfig(proto.Message): + r"""The configuration settings for the Airflow web server App Engine + instance. Supported for Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + Attributes: + machine_type (str): + Optional. Machine type on which Airflow web + server is running. It has to be one of: + composer-n1-webserver-2, composer-n1-webserver-4 + or composer-n1-webserver-8. + If not specified, composer-n1-webserver-2 will + be used. Value custom is returned only in + response, if Airflow web server parameters were + manually changed to a non-standard values. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EncryptionConfig(proto.Message): + r"""The encryption options for the Cloud Composer environment and its + dependencies. Supported for Cloud Composer environments in versions + composer-1.\ *.*-airflow-*.*.*. + + Attributes: + kms_key_name (str): + Optional. Customer-managed Encryption Key + available through Google's Key Management + Service. Cannot be updated. If not specified, + Google-managed key will be used. + """ + + kms_key_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class MaintenanceWindow(proto.Message): + r"""The configuration settings for Cloud Composer maintenance window. + The following example: + + :: + + { + "startTime":"2019-08-01T01:00:00Z" + "endTime":"2019-08-01T07:00:00Z" + "recurrence":"FREQ=WEEKLY;BYDAY=TU,WE" + } + + would define a maintenance window between 01 and 07 hours UTC during + each Tuesday and Wednesday. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Start time of the first recurrence + of the maintenance window. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Maintenance window end time. It is used only to + calculate the duration of the maintenance window. The value + for end_time must be in the future, relative to + ``start_time``. + recurrence (str): + Required. Maintenance window recurrence. Format is a subset + of `RFC-5545 `__ + ``RRULE``. The only allowed values for ``FREQ`` field are + ``FREQ=DAILY`` and ``FREQ=WEEKLY;BYDAY=...`` Example values: + ``FREQ=WEEKLY;BYDAY=TU,WE``, ``FREQ=DAILY``. + """ + + start_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, + ) + recurrence: str = proto.Field( + proto.STRING, + number=3, + ) + + +class WorkloadsConfig(proto.Message): + r"""The Kubernetes workloads configuration for GKE cluster associated + with the Cloud Composer environment. Supported for Cloud Composer + environments in versions composer-2.\ *.*-airflow-*.*.\* and newer. + + Attributes: + scheduler (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig.SchedulerResource): + Optional. Resources used by Airflow + schedulers. + web_server (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig.WebServerResource): + Optional. Resources used by Airflow web + server. + worker (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig.WorkerResource): + Optional. Resources used by Airflow workers. + triggerer (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig.TriggererResource): + Optional. Resources used by Airflow + triggerers. + dag_processor (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig.DagProcessorResource): + Optional. Resources used by Airflow DAG processors. + + This field is supported for Cloud Composer environments in + versions composer-3-airflow-\ *.*.\ *-build.* and newer. + """ + + class SchedulerResource(proto.Message): + r"""Configuration for resources used by Airflow schedulers. + + Attributes: + cpu (float): + Optional. CPU request and limit for a single + Airflow scheduler replica. + memory_gb (float): + Optional. Memory (GB) request and limit for a + single Airflow scheduler replica. + storage_gb (float): + Optional. Storage (GB) request and limit for + a single Airflow scheduler replica. + count (int): + Optional. The number of schedulers. + """ + + cpu: float = proto.Field( + proto.FLOAT, + number=1, + ) + memory_gb: float = proto.Field( + proto.FLOAT, + number=2, + ) + storage_gb: float = proto.Field( + proto.FLOAT, + number=3, + ) + count: int = proto.Field( + proto.INT32, + number=4, + ) + + class WebServerResource(proto.Message): + r"""Configuration for resources used by Airflow web server. + + Attributes: + cpu (float): + Optional. CPU request and limit for Airflow + web server. + memory_gb (float): + Optional. Memory (GB) request and limit for + Airflow web server. + storage_gb (float): + Optional. Storage (GB) request and limit for + Airflow web server. + """ + + cpu: float = proto.Field( + proto.FLOAT, + number=1, + ) + memory_gb: float = proto.Field( + proto.FLOAT, + number=2, + ) + storage_gb: float = proto.Field( + proto.FLOAT, + number=3, + ) + + class WorkerResource(proto.Message): + r"""Configuration for resources used by Airflow workers. + + Attributes: + cpu (float): + Optional. CPU request and limit for a single + Airflow worker replica. + memory_gb (float): + Optional. Memory (GB) request and limit for a + single Airflow worker replica. + storage_gb (float): + Optional. Storage (GB) request and limit for + a single Airflow worker replica. + min_count (int): + Optional. Minimum number of workers for + autoscaling. + max_count (int): + Optional. Maximum number of workers for + autoscaling. + """ + + cpu: float = proto.Field( + proto.FLOAT, + number=1, + ) + memory_gb: float = proto.Field( + proto.FLOAT, + number=2, + ) + storage_gb: float = proto.Field( + proto.FLOAT, + number=3, + ) + min_count: int = proto.Field( + proto.INT32, + number=4, + ) + max_count: int = proto.Field( + proto.INT32, + number=5, + ) + + class TriggererResource(proto.Message): + r"""Configuration for resources used by Airflow triggerers. + + Attributes: + count (int): + Optional. The number of triggerers. + cpu (float): + Optional. CPU request and limit for a single + Airflow triggerer replica. + memory_gb (float): + Optional. Memory (GB) request and limit for a + single Airflow triggerer replica. + """ + + count: int = proto.Field( + proto.INT32, + number=1, + ) + cpu: float = proto.Field( + proto.FLOAT, + number=2, + ) + memory_gb: float = proto.Field( + proto.FLOAT, + number=3, + ) + + class DagProcessorResource(proto.Message): + r"""Configuration for resources used by Airflow DAG processors. + + This field is supported for Cloud Composer environments in versions + composer-3-airflow-\ *.*.\ *-build.* and newer. + + Attributes: + cpu (float): + Optional. CPU request and limit for a single + Airflow DAG processor replica. + memory_gb (float): + Optional. Memory (GB) request and limit for a + single Airflow DAG processor replica. + storage_gb (float): + Optional. Storage (GB) request and limit for + a single Airflow DAG processor replica. + count (int): + Optional. The number of DAG processors. If + not provided or set to 0, a single DAG processor + instance will be created. + """ + + cpu: float = proto.Field( + proto.FLOAT, + number=1, + ) + memory_gb: float = proto.Field( + proto.FLOAT, + number=2, + ) + storage_gb: float = proto.Field( + proto.FLOAT, + number=3, + ) + count: int = proto.Field( + proto.INT32, + number=4, + ) + + scheduler: SchedulerResource = proto.Field( + proto.MESSAGE, + number=1, + message=SchedulerResource, + ) + web_server: WebServerResource = proto.Field( + proto.MESSAGE, + number=2, + message=WebServerResource, + ) + worker: WorkerResource = proto.Field( + proto.MESSAGE, + number=3, + message=WorkerResource, + ) + triggerer: TriggererResource = proto.Field( + proto.MESSAGE, + number=4, + message=TriggererResource, + ) + dag_processor: DagProcessorResource = proto.Field( + proto.MESSAGE, + number=5, + message=DagProcessorResource, + ) + + +class DataRetentionConfig(proto.Message): + r"""The configuration setting for Airflow database data retention + mechanism. + + Attributes: + airflow_database_retention_days (int): + Optional. The number of days describing for + how long to store event-based records in airflow + database. If the retention mechanism is enabled + this value must be a positive integer otherwise, + value should be set to 0. + task_logs_retention_config (google.cloud.orchestration.airflow.service_v1beta1.types.TaskLogsRetentionConfig): + Optional. The configuration settings for task + logs retention + airflow_metadata_retention_config (google.cloud.orchestration.airflow.service_v1beta1.types.AirflowMetadataRetentionPolicyConfig): + Optional. The retention policy for airflow + metadata database. + """ + + airflow_database_retention_days: int = proto.Field( + proto.INT32, + number=1, + ) + task_logs_retention_config: 'TaskLogsRetentionConfig' = proto.Field( + proto.MESSAGE, + number=4, + message='TaskLogsRetentionConfig', + ) + airflow_metadata_retention_config: 'AirflowMetadataRetentionPolicyConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='AirflowMetadataRetentionPolicyConfig', + ) + + +class TaskLogsRetentionConfig(proto.Message): + r"""The configuration setting for Task Logs. + + Attributes: + storage_mode (google.cloud.orchestration.airflow.service_v1beta1.types.TaskLogsRetentionConfig.TaskLogsStorageMode): + Optional. The mode of storage for Airflow + workers task logs. + """ + class TaskLogsStorageMode(proto.Enum): + r"""The definition of task_logs_storage_mode. + + Values: + TASK_LOGS_STORAGE_MODE_UNSPECIFIED (0): + This configuration is not specified by the + user. + CLOUD_LOGGING_AND_CLOUD_STORAGE (1): + Store task logs in Cloud Logging and in the + environment's Cloud Storage bucket. + CLOUD_LOGGING_ONLY (2): + Store task logs in Cloud Logging only. + """ + TASK_LOGS_STORAGE_MODE_UNSPECIFIED = 0 + CLOUD_LOGGING_AND_CLOUD_STORAGE = 1 + CLOUD_LOGGING_ONLY = 2 + + storage_mode: TaskLogsStorageMode = proto.Field( + proto.ENUM, + number=2, + enum=TaskLogsStorageMode, + ) + + +class AirflowMetadataRetentionPolicyConfig(proto.Message): + r"""The policy for airflow metadata database retention. + + Attributes: + retention_mode (google.cloud.orchestration.airflow.service_v1beta1.types.AirflowMetadataRetentionPolicyConfig.RetentionMode): + Optional. Retention can be either enabled or + disabled. + retention_days (int): + Optional. How many days data should be + retained for. + """ + class RetentionMode(proto.Enum): + r"""Describes retention policy. + + Values: + RETENTION_MODE_UNSPECIFIED (0): + Default mode doesn't change environment + parameters. + RETENTION_MODE_ENABLED (1): + Retention policy is enabled. + RETENTION_MODE_DISABLED (2): + Retention policy is disabled. + """ + RETENTION_MODE_UNSPECIFIED = 0 + RETENTION_MODE_ENABLED = 1 + RETENTION_MODE_DISABLED = 2 + + retention_mode: RetentionMode = proto.Field( + proto.ENUM, + number=1, + enum=RetentionMode, + ) + retention_days: int = proto.Field( + proto.INT32, + number=2, + ) + + +class StorageConfig(proto.Message): + r"""The configuration for data storage in the environment. + + Attributes: + bucket (str): + Optional. The name of the Cloud Storage bucket used by the + environment. No ``gs://`` prefix. + """ + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RecoveryConfig(proto.Message): + r"""The Recovery settings of an environment. + + Attributes: + scheduled_snapshots_config (google.cloud.orchestration.airflow.service_v1beta1.types.ScheduledSnapshotsConfig): + Optional. The configuration for scheduled + snapshot creation mechanism. + """ + + scheduled_snapshots_config: 'ScheduledSnapshotsConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='ScheduledSnapshotsConfig', + ) + + +class ScheduledSnapshotsConfig(proto.Message): + r"""The configuration for scheduled snapshot creation mechanism. + + Attributes: + enabled (bool): + Optional. Whether scheduled snapshots + creation is enabled. + snapshot_location (str): + Optional. The Cloud Storage location for + storing automatically created snapshots. + snapshot_creation_schedule (str): + Optional. The cron expression representing + the time when snapshots creation mechanism runs. + This field is subject to additional validation + around frequency of execution. + time_zone (str): + Optional. Time zone that sets the context to interpret + snapshot_creation_schedule. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + snapshot_location: str = proto.Field( + proto.STRING, + number=6, + ) + snapshot_creation_schedule: str = proto.Field( + proto.STRING, + number=3, + ) + time_zone: str = proto.Field( + proto.STRING, + number=5, + ) + + +class MasterAuthorizedNetworksConfig(proto.Message): + r"""Configuration options for the master authorized networks + feature. Enabled master authorized networks will disallow all + external traffic to access Kubernetes master through HTTPS + except traffic from the given CIDR blocks, Google Compute Engine + Public IPs and Google Prod IPs. + + Attributes: + enabled (bool): + Whether or not master authorized networks + feature is enabled. + cidr_blocks (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.MasterAuthorizedNetworksConfig.CidrBlock]): + Up to 50 external networks that could access + Kubernetes master through HTTPS. + """ + + class CidrBlock(proto.Message): + r"""CIDR block with an optional name. + + Attributes: + display_name (str): + User-defined name that identifies the CIDR + block. + cidr_block (str): + CIDR block that must be specified in CIDR + notation. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + cidr_block: str = proto.Field( + proto.STRING, + number=2, + ) + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + cidr_blocks: MutableSequence[CidrBlock] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=CidrBlock, + ) + + +class CloudDataLineageIntegration(proto.Message): + r"""Configuration for Cloud Data Lineage integration. + + Attributes: + enabled (bool): + Optional. Whether or not Cloud Data Lineage + integration is enabled. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class Environment(proto.Message): + r"""An environment for running orchestration tasks. + + Attributes: + name (str): + Identifier. The resource name of the + environment, in the form: + "projects/{projectId}/locations/{locationId}/environments/{environmentId}" + + EnvironmentId must start with a lowercase letter + followed by up to 63 lowercase letters, numbers, + or hyphens, and cannot end with a hyphen. + config (google.cloud.orchestration.airflow.service_v1beta1.types.EnvironmentConfig): + Optional. Configuration parameters for this + environment. + uuid (str): + Output only. The UUID (Universally Unique + IDentifier) associated with this environment. + This value is generated when the environment is + created. + state (google.cloud.orchestration.airflow.service_v1beta1.types.Environment.State): + The current state of the environment. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + environment was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + environment was last modified. + labels (MutableMapping[str, str]): + Optional. User-defined labels for this environment. The + labels map can contain no more than 64 entries. Entries of + the labels map are UTF8 strings that comply with the + following restrictions: + + - Keys must conform to regexp: + [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62} + - Values must conform to regexp: + [\p{Ll}\p{Lo}\p{N}_-]{0,63} + - Both keys and values are additionally constrained to be + <= 128 bytes in size. + satisfies_pzs (bool): + Output only. Reserved for future use. + satisfies_pzi (bool): + Output only. Reserved for future use. + storage_config (google.cloud.orchestration.airflow.service_v1beta1.types.StorageConfig): + Optional. Storage configuration for this + environment. + """ + class State(proto.Enum): + r"""State of the environment. + + Values: + STATE_UNSPECIFIED (0): + The state of the environment is unknown. + CREATING (1): + The environment is in the process of being + created. + RUNNING (2): + The environment is currently running and + healthy. It is ready for use. + UPDATING (3): + The environment is being updated. It remains + usable but cannot receive additional update + requests or be deleted at this time. + DELETING (4): + The environment is undergoing deletion. It + cannot be used. + ERROR (5): + The environment has encountered an error and + cannot be used. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + RUNNING = 2 + UPDATING = 3 + DELETING = 4 + ERROR = 5 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + config: 'EnvironmentConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='EnvironmentConfig', + ) + uuid: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=8, + ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=10, + ) + storage_config: 'StorageConfig' = proto.Field( + proto.MESSAGE, + number=9, + message='StorageConfig', + ) + + +class CheckUpgradeRequest(proto.Message): + r"""Request to check whether image upgrade will succeed. + + Attributes: + environment (str): + The resource name of the environment to check + upgrade for, in the form: + + "projects/{projectId}/locations/{locationId}/environments/{environmentId}". + image_version (str): + The version of the software running in the environment. This + encapsulates both the version of Cloud Composer + functionality and the version of Apache Airflow. It must + match the regular expression + ``composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)``. + When used as input, the server also checks if the provided + version is supported and denies the request for an + unsupported version. + + The Cloud Composer portion of the image version is a full + `semantic version `__, or an alias in + the form of major version number or ``latest``. When an + alias is provided, the server replaces it with the current + Cloud Composer version that satisfies the alias. + + The Apache Airflow portion of the image version is a full + semantic version that points to one of the supported Apache + Airflow versions, or an alias in the form of only major or + major.minor versions specified. When an alias is provided, + the server replaces it with the latest Apache Airflow + version that satisfies the alias and is supported in the + given Cloud Composer version. + + In all cases, the resolved image version is stored in the + same field. + + See also `version + list `__ + and `versioning + overview `__. + """ + + environment: str = proto.Field( + proto.STRING, + number=1, + ) + image_version: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CheckUpgradeResponse(proto.Message): + r"""Message containing information about the result of an upgrade + check operation. + + Attributes: + build_log_uri (str): + Output only. Url for a docker build log of an + upgraded image. + contains_pypi_modules_conflict (google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeResponse.ConflictResult): + Output only. Whether build has succeeded or + failed on modules conflicts. + pypi_conflict_build_log_extract (str): + Output only. Extract from a docker image + build log containing information about pypi + modules conflicts. + image_version (str): + Composer image for which the build was + happening. + pypi_dependencies (MutableMapping[str, str]): + Pypi dependencies specified in the + environment configuration, at the time when the + build was triggered. + """ + class ConflictResult(proto.Enum): + r"""Whether there were python modules conflict during image + build. + + Values: + CONFLICT_RESULT_UNSPECIFIED (0): + It is unknown whether build had conflicts or + not. + CONFLICT (1): + There were python packages conflicts. + NO_CONFLICT (2): + There were no python packages conflicts. + """ + CONFLICT_RESULT_UNSPECIFIED = 0 + CONFLICT = 1 + NO_CONFLICT = 2 + + build_log_uri: str = proto.Field( + proto.STRING, + number=1, + ) + contains_pypi_modules_conflict: ConflictResult = proto.Field( + proto.ENUM, + number=4, + enum=ConflictResult, + ) + pypi_conflict_build_log_extract: str = proto.Field( + proto.STRING, + number=3, + ) + image_version: str = proto.Field( + proto.STRING, + number=5, + ) + pypi_dependencies: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/image_versions.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/image_versions.py new file mode 100644 index 000000000000..656f44349e78 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/image_versions.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.orchestration.airflow.service.v1beta1', + manifest={ + 'ListImageVersionsRequest', + 'ListImageVersionsResponse', + 'ImageVersion', + }, +) + + +class ListImageVersionsRequest(proto.Message): + r"""List ImageVersions in a project and location. + + Attributes: + parent (str): + List ImageVersions in the given project and + location, in the form: + "projects/{projectId}/locations/{locationId}". + page_size (int): + The maximum number of image_versions to return. + page_token (str): + The next_page_token value returned from a previous List + request, if any. + include_past_releases (bool): + Whether or not image versions from old + releases should be included. + """ + + 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, + ) + include_past_releases: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListImageVersionsResponse(proto.Message): + r"""The ImageVersions in a project and location. + + Attributes: + image_versions (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.ImageVersion]): + The list of supported ImageVersions in a + location. + next_page_token (str): + The page token used to query for the next + page if one exists. + """ + + @property + def raw_page(self): + return self + + image_versions: MutableSequence['ImageVersion'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ImageVersion', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ImageVersion(proto.Message): + r"""Image Version information + + Attributes: + image_version_id (str): + The string identifier of the ImageVersion, in + the form: "composer-x.y.z-airflow-a.b.c". + is_default (bool): + Whether this is the default ImageVersion used + by Composer during environment creation if no + input ImageVersion is specified. + supported_python_versions (MutableSequence[str]): + supported python versions + release_date (google.type.date_pb2.Date): + The date of the version release. + creation_disabled (bool): + Whether it is impossible to create an + environment with the image version. + upgrade_disabled (bool): + Whether it is impossible to upgrade an + environment running with the image version. + """ + + image_version_id: str = proto.Field( + proto.STRING, + number=1, + ) + is_default: bool = proto.Field( + proto.BOOL, + number=2, + ) + supported_python_versions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + release_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=4, + message=date_pb2.Date, + ) + creation_disabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + upgrade_disabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py new file mode 100644 index 000000000000..585838b342e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service.v1beta1', + manifest={ + 'OperationMetadata', + }, +) + + +class OperationMetadata(proto.Message): + r"""Metadata describing an operation. + + Attributes: + state (google.cloud.orchestration.airflow.service_v1beta1.types.OperationMetadata.State): + Output only. The current operation state. + operation_type (google.cloud.orchestration.airflow.service_v1beta1.types.OperationMetadata.Type): + Output only. The type of operation being + performed. + resource (str): + Output only. The resource being operated on, as a `relative + resource + name `__. + resource_uuid (str): + Output only. The UUID of the resource being + operated on. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + submitted to the server. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the operation + terminated, regardless of its success. This + field is unset if the operation is still + ongoing. + """ + class State(proto.Enum): + r"""An enum describing the overall state of an operation. + + Values: + STATE_UNSPECIFIED (0): + Unused. + PENDING (1): + The operation has been created but is not yet + started. + RUNNING (2): + The operation is underway. + SUCCESSFUL (3): + The operation completed successfully. + FAILED (4): + The operation is no longer running but did + not succeed. + """ + STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + SUCCESSFUL = 3 + FAILED = 4 + + class Type(proto.Enum): + r"""Type of longrunning operation. + + Values: + TYPE_UNSPECIFIED (0): + Unused. + CREATE (1): + A resource creation operation. + DELETE (2): + A resource deletion operation. + UPDATE (3): + A resource update operation. + CHECK (4): + A resource check operation. + SAVE_SNAPSHOT (5): + Saves snapshot of the resource operation. + LOAD_SNAPSHOT (6): + Loads snapshot of the resource operation. + DATABASE_FAILOVER (7): + Triggers failover of environment's Cloud SQL + instance (only for highly resilient + environments). + """ + TYPE_UNSPECIFIED = 0 + CREATE = 1 + DELETE = 2 + UPDATE = 3 + CHECK = 4 + SAVE_SNAPSHOT = 5 + LOAD_SNAPSHOT = 6 + DATABASE_FAILOVER = 7 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + operation_type: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + resource: str = proto.Field( + proto.STRING, + number=3, + ) + resource_uuid: str = proto.Field( + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/mypy.ini b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/noxfile.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/noxfile.py new file mode 100644 index 000000000000..45aed3ec3bd0 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow-service' + +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/orchestration/airflow/service_v1beta1/', + '--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/orchestration/airflow/service_v1beta1/', + '--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-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py new file mode 100644 index 000000000000..6baa8c041043 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_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 CheckUpgrade +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_CheckUpgrade_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.orchestration.airflow import service_v1beta1 + + +async def sample_check_upgrade(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.CheckUpgradeRequest( + ) + + # Make the request + operation = client.check_upgrade(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_CheckUpgrade_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py new file mode 100644 index 000000000000..7f42892feecf --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_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 CheckUpgrade +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_CheckUpgrade_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.orchestration.airflow import service_v1beta1 + + +def sample_check_upgrade(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.CheckUpgradeRequest( + ) + + # Make the request + operation = client.check_upgrade(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_CheckUpgrade_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py new file mode 100644 index 000000000000..d5cd4346b3ff --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_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 CreateEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_CreateEnvironment_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.orchestration.airflow import service_v1beta1 + + +async def sample_create_environment(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateEnvironmentRequest( + ) + + # Make the request + operation = client.create_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_CreateEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py new file mode 100644 index 000000000000..e7b8bb84502c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_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 CreateEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_CreateEnvironment_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.orchestration.airflow import service_v1beta1 + + +def sample_create_environment(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateEnvironmentRequest( + ) + + # Make the request + operation = client.create_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_CreateEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_async.py new file mode 100644 index 000000000000..ced9415f1df3 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_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 CreateUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 + + +async def sample_create_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateUserWorkloadsConfigMapRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_sync.py new file mode 100644 index 000000000000..b34964ee1e0b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_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 CreateUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 + + +def sample_create_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateUserWorkloadsConfigMapRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_async.py new file mode 100644 index 000000000000..806219d891ab --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_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 CreateUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 + + +async def sample_create_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateUserWorkloadsSecretRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_sync.py new file mode 100644 index 000000000000..00ab0b127a15 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_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 CreateUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 + + +def sample_create_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.CreateUserWorkloadsSecretRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py new file mode 100644 index 000000000000..030ec030de2c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_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 DatabaseFailover +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_DatabaseFailover_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.orchestration.airflow import service_v1beta1 + + +async def sample_database_failover(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.DatabaseFailoverRequest( + ) + + # Make the request + operation = client.database_failover(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_DatabaseFailover_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py new file mode 100644 index 000000000000..9ee79ca04dec --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_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 DatabaseFailover +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_DatabaseFailover_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.orchestration.airflow import service_v1beta1 + + +def sample_database_failover(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.DatabaseFailoverRequest( + ) + + # Make the request + operation = client.database_failover(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_DatabaseFailover_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py new file mode 100644 index 000000000000..81e42e44a226 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_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 DeleteEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_DeleteEnvironment_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.orchestration.airflow import service_v1beta1 + + +async def sample_delete_environment(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteEnvironmentRequest( + ) + + # Make the request + operation = client.delete_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_DeleteEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py new file mode 100644 index 000000000000..797acab85ac0 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_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 DeleteEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_DeleteEnvironment_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.orchestration.airflow import service_v1beta1 + + +def sample_delete_environment(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteEnvironmentRequest( + ) + + # Make the request + operation = client.delete_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_DeleteEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py new file mode 100644 index 000000000000..4fd28d601d04 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 + + +async def sample_delete_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_workloads_config_map(request=request) + + +# [END composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py new file mode 100644 index 000000000000..8666cf16962e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 + + +def sample_delete_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + client.delete_user_workloads_config_map(request=request) + + +# [END composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py new file mode 100644 index 000000000000..bad25cfa30ca --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 + + +async def sample_delete_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + await client.delete_user_workloads_secret(request=request) + + +# [END composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py new file mode 100644 index 000000000000..846c5a894a20 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 + + +def sample_delete_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.DeleteUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + client.delete_user_workloads_secret(request=request) + + +# [END composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py new file mode 100644 index 000000000000..b9fe11cb8cc4 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_ExecuteAirflowCommand_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.orchestration.airflow import service_v1beta1 + + +async def sample_execute_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ExecuteAirflowCommandRequest( + ) + + # Make the request + response = await client.execute_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_ExecuteAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py new file mode 100644 index 000000000000..092e93e88fa8 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_ExecuteAirflowCommand_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.orchestration.airflow import service_v1beta1 + + +def sample_execute_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.ExecuteAirflowCommandRequest( + ) + + # Make the request + response = client.execute_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_ExecuteAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py new file mode 100644 index 000000000000..57aa9678bc5f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_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 FetchDatabaseProperties +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_FetchDatabaseProperties_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.orchestration.airflow import service_v1beta1 + + +async def sample_fetch_database_properties(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.FetchDatabasePropertiesRequest( + environment="environment_value", + ) + + # Make the request + response = await client.fetch_database_properties(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_FetchDatabaseProperties_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py new file mode 100644 index 000000000000..83de56e5deec --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_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 FetchDatabaseProperties +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_FetchDatabaseProperties_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.orchestration.airflow import service_v1beta1 + + +def sample_fetch_database_properties(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.FetchDatabasePropertiesRequest( + environment="environment_value", + ) + + # Make the request + response = client.fetch_database_properties(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_FetchDatabaseProperties_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py new file mode 100644 index 000000000000..2fd85676181a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_GetEnvironment_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.orchestration.airflow import service_v1beta1 + + +async def sample_get_environment(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.GetEnvironmentRequest( + ) + + # Make the request + response = await client.get_environment(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_GetEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py new file mode 100644 index 000000000000..5848891a5a2f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_GetEnvironment_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.orchestration.airflow import service_v1beta1 + + +def sample_get_environment(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.GetEnvironmentRequest( + ) + + # Make the request + response = client.get_environment(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_GetEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_async.py new file mode 100644 index 000000000000..db6fe57f2cb0 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_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 GetUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 + + +async def sample_get_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.GetUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_sync.py new file mode 100644 index 000000000000..03fdda66a9e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_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 GetUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 + + +def sample_get_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.GetUserWorkloadsConfigMapRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_async.py new file mode 100644 index 000000000000..c415f1ba12ac --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_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 GetUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 + + +async def sample_get_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.GetUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_sync.py new file mode 100644 index 000000000000..d7e634fc392f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_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 GetUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 + + +def sample_get_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.GetUserWorkloadsSecretRequest( + name="name_value", + ) + + # Make the request + response = client.get_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py new file mode 100644 index 000000000000..accc178dfc2f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_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 ListEnvironments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_ListEnvironments_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.orchestration.airflow import service_v1beta1 + + +async def sample_list_environments(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ListEnvironmentsRequest( + ) + + # Make the request + page_result = client.list_environments(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END composer_v1beta1_generated_Environments_ListEnvironments_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py new file mode 100644 index 000000000000..62b54c259c23 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_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 ListEnvironments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_ListEnvironments_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.orchestration.airflow import service_v1beta1 + + +def sample_list_environments(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.ListEnvironmentsRequest( + ) + + # Make the request + page_result = client.list_environments(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END composer_v1beta1_generated_Environments_ListEnvironments_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_async.py new file mode 100644 index 000000000000..6911e8a42394 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_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 ListUserWorkloadsConfigMaps +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_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.orchestration.airflow import service_v1beta1 + + +async def sample_list_user_workloads_config_maps(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ListUserWorkloadsConfigMapsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_config_maps(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_sync.py new file mode 100644 index 000000000000..80f6c060f7fb --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_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 ListUserWorkloadsConfigMaps +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_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.orchestration.airflow import service_v1beta1 + + +def sample_list_user_workloads_config_maps(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.ListUserWorkloadsConfigMapsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_config_maps(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_async.py new file mode 100644 index 000000000000..4e0fde2889ef --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_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 ListUserWorkloadsSecrets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_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.orchestration.airflow import service_v1beta1 + + +async def sample_list_user_workloads_secrets(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ListUserWorkloadsSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_secrets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_sync.py new file mode 100644 index 000000000000..df5ea329609c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_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 ListUserWorkloadsSecrets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_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.orchestration.airflow import service_v1beta1 + + +def sample_list_user_workloads_secrets(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.ListUserWorkloadsSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_workloads_secrets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_async.py new file mode 100644 index 000000000000..ce4aeeea2e44 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_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 ListWorkloads +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_ListWorkloads_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.orchestration.airflow import service_v1beta1 + + +async def sample_list_workloads(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END composer_v1beta1_generated_Environments_ListWorkloads_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_sync.py new file mode 100644 index 000000000000..eef4cf388e9d --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_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 ListWorkloads +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_ListWorkloads_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.orchestration.airflow import service_v1beta1 + + +def sample_list_workloads(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END composer_v1beta1_generated_Environments_ListWorkloads_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py new file mode 100644 index 000000000000..3c74e656e14a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_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 LoadSnapshot +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_LoadSnapshot_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.orchestration.airflow import service_v1beta1 + + +async def sample_load_snapshot(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.LoadSnapshotRequest( + ) + + # Make the request + operation = client.load_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_LoadSnapshot_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py new file mode 100644 index 000000000000..2c6363265456 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_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 LoadSnapshot +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_LoadSnapshot_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.orchestration.airflow import service_v1beta1 + + +def sample_load_snapshot(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.LoadSnapshotRequest( + ) + + # Make the request + operation = client.load_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_LoadSnapshot_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py new file mode 100644 index 000000000000..72f7769e2133 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PollAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_PollAirflowCommand_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.orchestration.airflow import service_v1beta1 + + +async def sample_poll_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.PollAirflowCommandRequest( + ) + + # Make the request + response = await client.poll_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_PollAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py new file mode 100644 index 000000000000..9d3cac31ca45 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PollAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_PollAirflowCommand_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.orchestration.airflow import service_v1beta1 + + +def sample_poll_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.PollAirflowCommandRequest( + ) + + # Make the request + response = client.poll_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_PollAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py new file mode 100644 index 000000000000..7c3695c9c059 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_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 RestartWebServer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_RestartWebServer_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.orchestration.airflow import service_v1beta1 + + +async def sample_restart_web_server(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.RestartWebServerRequest( + ) + + # Make the request + operation = client.restart_web_server(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_RestartWebServer_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py new file mode 100644 index 000000000000..45bdc32d4414 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_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 RestartWebServer +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_RestartWebServer_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.orchestration.airflow import service_v1beta1 + + +def sample_restart_web_server(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.RestartWebServerRequest( + ) + + # Make the request + operation = client.restart_web_server(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_RestartWebServer_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py new file mode 100644 index 000000000000..e1633fb95150 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_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 SaveSnapshot +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_SaveSnapshot_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.orchestration.airflow import service_v1beta1 + + +async def sample_save_snapshot(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.SaveSnapshotRequest( + ) + + # Make the request + operation = client.save_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_SaveSnapshot_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py new file mode 100644 index 000000000000..2cc6efa01f67 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_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 SaveSnapshot +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_SaveSnapshot_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.orchestration.airflow import service_v1beta1 + + +def sample_save_snapshot(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.SaveSnapshotRequest( + ) + + # Make the request + operation = client.save_snapshot(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_SaveSnapshot_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py new file mode 100644 index 000000000000..fb9f01196fa1 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StopAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_StopAirflowCommand_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.orchestration.airflow import service_v1beta1 + + +async def sample_stop_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.StopAirflowCommandRequest( + ) + + # Make the request + response = await client.stop_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_StopAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py new file mode 100644 index 000000000000..04af2493c240 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for StopAirflowCommand +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_StopAirflowCommand_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.orchestration.airflow import service_v1beta1 + + +def sample_stop_airflow_command(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.StopAirflowCommandRequest( + ) + + # Make the request + response = client.stop_airflow_command(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_StopAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py new file mode 100644 index 000000000000..2ca35a97a361 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_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 UpdateEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_UpdateEnvironment_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.orchestration.airflow import service_v1beta1 + + +async def sample_update_environment(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateEnvironmentRequest( + ) + + # Make the request + operation = client.update_environment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_UpdateEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py new file mode 100644 index 000000000000..8414feba820a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_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 UpdateEnvironment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_UpdateEnvironment_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.orchestration.airflow import service_v1beta1 + + +def sample_update_environment(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateEnvironmentRequest( + ) + + # Make the request + operation = client.update_environment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_UpdateEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py new file mode 100644 index 000000000000..e14bc1342606 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 + + +async def sample_update_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateUserWorkloadsConfigMapRequest( + ) + + # Make the request + response = await client.update_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py new file mode 100644 index 000000000000..5bc57738762e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserWorkloadsConfigMap +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 + + +def sample_update_user_workloads_config_map(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateUserWorkloadsConfigMapRequest( + ) + + # Make the request + response = client.update_user_workloads_config_map(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_async.py new file mode 100644 index 000000000000..e200b6782d9c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 + + +async def sample_update_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateUserWorkloadsSecretRequest( + ) + + # Make the request + response = await client.update_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py new file mode 100644 index 000000000000..50022404644a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUserWorkloadsSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 + + +def sample_update_user_workloads_secret(): + # Create a client + client = service_v1beta1.EnvironmentsClient() + + # Initialize request argument(s) + request = service_v1beta1.UpdateUserWorkloadsSecretRequest( + ) + + # Make the request + response = client.update_user_workloads_secret(request=request) + + # Handle the response + print(response) + +# [END composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_async.py new file mode 100644 index 000000000000..309c6f9eeab4 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_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 ListImageVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_ImageVersions_ListImageVersions_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.orchestration.airflow import service_v1beta1 + + +async def sample_list_image_versions(): + # Create a client + client = service_v1beta1.ImageVersionsAsyncClient() + + # Initialize request argument(s) + request = service_v1beta1.ListImageVersionsRequest( + ) + + # Make the request + page_result = client.list_image_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END composer_v1beta1_generated_ImageVersions_ListImageVersions_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_sync.py new file mode 100644 index 000000000000..86a3b0c52064 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_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 ListImageVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-orchestration-airflow-service + + +# [START composer_v1beta1_generated_ImageVersions_ListImageVersions_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.orchestration.airflow import service_v1beta1 + + +def sample_list_image_versions(): + # Create a client + client = service_v1beta1.ImageVersionsClient() + + # Initialize request argument(s) + request = service_v1beta1.ListImageVersionsRequest( + ) + + # Make the request + page_result = client.list_image_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END composer_v1beta1_generated_ImageVersions_ListImageVersions_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json new file mode 100644 index 000000000000..5dde9a47fdfc --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json @@ -0,0 +1,4157 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.orchestration.airflow.service.v1beta1", + "version": "v1beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-orchestration-airflow-service", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.check_upgrade", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CheckUpgrade", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "CheckUpgrade" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeRequest" + }, + { + "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": "check_upgrade" + }, + "description": "Sample for CheckUpgrade", + "file": "composer_v1beta1_generated_environments_check_upgrade_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_CheckUpgrade_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_check_upgrade_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.check_upgrade", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CheckUpgrade", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "CheckUpgrade" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeRequest" + }, + { + "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": "check_upgrade" + }, + "description": "Sample for CheckUpgrade", + "file": "composer_v1beta1_generated_environments_check_upgrade_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_CheckUpgrade_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_check_upgrade_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.create_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateEnvironmentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "environment", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.Environment" + }, + { + "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_environment" + }, + "description": "Sample for CreateEnvironment", + "file": "composer_v1beta1_generated_environments_create_environment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_CreateEnvironment_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_create_environment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateEnvironmentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "environment", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.Environment" + }, + { + "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_environment" + }, + "description": "Sample for CreateEnvironment", + "file": "composer_v1beta1_generated_environments_create_environment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_CreateEnvironment_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_create_environment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.create_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsConfigMapRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_workloads_config_map", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", + "shortName": "create_user_workloads_config_map" + }, + "description": "Sample for CreateUserWorkloadsConfigMap", + "file": "composer_v1beta1_generated_environments_create_user_workloads_config_map_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_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": "composer_v1beta1_generated_environments_create_user_workloads_config_map_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsConfigMapRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_workloads_config_map", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", + "shortName": "create_user_workloads_config_map" + }, + "description": "Sample for CreateUserWorkloadsConfigMap", + "file": "composer_v1beta1_generated_environments_create_user_workloads_config_map_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_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": "composer_v1beta1_generated_environments_create_user_workloads_config_map_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.create_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsSecretRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_workloads_secret", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", + "shortName": "create_user_workloads_secret" + }, + "description": "Sample for CreateUserWorkloadsSecret", + "file": "composer_v1beta1_generated_environments_create_user_workloads_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_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": "composer_v1beta1_generated_environments_create_user_workloads_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "CreateUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsSecretRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_workloads_secret", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", + "shortName": "create_user_workloads_secret" + }, + "description": "Sample for CreateUserWorkloadsSecret", + "file": "composer_v1beta1_generated_environments_create_user_workloads_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_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": "composer_v1beta1_generated_environments_create_user_workloads_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.database_failover", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DatabaseFailover", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "DatabaseFailover" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseFailoverRequest" + }, + { + "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": "database_failover" + }, + "description": "Sample for DatabaseFailover", + "file": "composer_v1beta1_generated_environments_database_failover_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_DatabaseFailover_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_database_failover_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.database_failover", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DatabaseFailover", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "DatabaseFailover" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseFailoverRequest" + }, + { + "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": "database_failover" + }, + "description": "Sample for DatabaseFailover", + "file": "composer_v1beta1_generated_environments_database_failover_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_DatabaseFailover_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_database_failover_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.delete_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteEnvironmentRequest" + }, + { + "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_environment" + }, + "description": "Sample for DeleteEnvironment", + "file": "composer_v1beta1_generated_environments_delete_environment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_DeleteEnvironment_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_delete_environment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.delete_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteEnvironmentRequest" + }, + { + "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_environment" + }, + "description": "Sample for DeleteEnvironment", + "file": "composer_v1beta1_generated_environments_delete_environment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_DeleteEnvironment_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_delete_environment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.delete_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsConfigMapRequest" + }, + { + "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]]]" + } + ], + "shortName": "delete_user_workloads_config_map" + }, + "description": "Sample for DeleteUserWorkloadsConfigMap", + "file": "composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.delete_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsConfigMapRequest" + }, + { + "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]]]" + } + ], + "shortName": "delete_user_workloads_config_map" + }, + "description": "Sample for DeleteUserWorkloadsConfigMap", + "file": "composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.delete_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsSecretRequest" + }, + { + "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]]]" + } + ], + "shortName": "delete_user_workloads_secret" + }, + "description": "Sample for DeleteUserWorkloadsSecret", + "file": "composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.delete_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "DeleteUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsSecretRequest" + }, + { + "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]]]" + } + ], + "shortName": "delete_user_workloads_secret" + }, + "description": "Sample for DeleteUserWorkloadsSecret", + "file": "composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.execute_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ExecuteAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "ExecuteAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandResponse", + "shortName": "execute_airflow_command" + }, + "description": "Sample for ExecuteAirflowCommand", + "file": "composer_v1beta1_generated_environments_execute_airflow_command_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_ExecuteAirflowCommand_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_execute_airflow_command_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.execute_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ExecuteAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "ExecuteAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandResponse", + "shortName": "execute_airflow_command" + }, + "description": "Sample for ExecuteAirflowCommand", + "file": "composer_v1beta1_generated_environments_execute_airflow_command_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_ExecuteAirflowCommand_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_execute_airflow_command_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.fetch_database_properties", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.FetchDatabaseProperties", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "FetchDatabaseProperties" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesResponse", + "shortName": "fetch_database_properties" + }, + "description": "Sample for FetchDatabaseProperties", + "file": "composer_v1beta1_generated_environments_fetch_database_properties_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_FetchDatabaseProperties_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": "composer_v1beta1_generated_environments_fetch_database_properties_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.fetch_database_properties", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.FetchDatabaseProperties", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "FetchDatabaseProperties" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesResponse", + "shortName": "fetch_database_properties" + }, + "description": "Sample for FetchDatabaseProperties", + "file": "composer_v1beta1_generated_environments_fetch_database_properties_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_FetchDatabaseProperties_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": "composer_v1beta1_generated_environments_fetch_database_properties_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.get_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "GetEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.types.Environment", + "shortName": "get_environment" + }, + "description": "Sample for GetEnvironment", + "file": "composer_v1beta1_generated_environments_get_environment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_GetEnvironment_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_get_environment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "GetEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.types.Environment", + "shortName": "get_environment" + }, + "description": "Sample for GetEnvironment", + "file": "composer_v1beta1_generated_environments_get_environment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_GetEnvironment_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_get_environment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.get_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "GetUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsConfigMapRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", + "shortName": "get_user_workloads_config_map" + }, + "description": "Sample for GetUserWorkloadsConfigMap", + "file": "composer_v1beta1_generated_environments_get_user_workloads_config_map_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_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": "composer_v1beta1_generated_environments_get_user_workloads_config_map_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "GetUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsConfigMapRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", + "shortName": "get_user_workloads_config_map" + }, + "description": "Sample for GetUserWorkloadsConfigMap", + "file": "composer_v1beta1_generated_environments_get_user_workloads_config_map_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_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": "composer_v1beta1_generated_environments_get_user_workloads_config_map_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.get_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "GetUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsSecretRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", + "shortName": "get_user_workloads_secret" + }, + "description": "Sample for GetUserWorkloadsSecret", + "file": "composer_v1beta1_generated_environments_get_user_workloads_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_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": "composer_v1beta1_generated_environments_get_user_workloads_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "GetUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsSecretRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", + "shortName": "get_user_workloads_secret" + }, + "description": "Sample for GetUserWorkloadsSecret", + "file": "composer_v1beta1_generated_environments_get_user_workloads_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_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": "composer_v1beta1_generated_environments_get_user_workloads_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.list_environments", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListEnvironments", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "ListEnvironments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsAsyncPager", + "shortName": "list_environments" + }, + "description": "Sample for ListEnvironments", + "file": "composer_v1beta1_generated_environments_list_environments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_ListEnvironments_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_list_environments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_environments", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListEnvironments", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "ListEnvironments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsPager", + "shortName": "list_environments" + }, + "description": "Sample for ListEnvironments", + "file": "composer_v1beta1_generated_environments_list_environments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_ListEnvironments_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_list_environments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.list_user_workloads_config_maps", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListUserWorkloadsConfigMaps", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "ListUserWorkloadsConfigMaps" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsConfigMapsAsyncPager", + "shortName": "list_user_workloads_config_maps" + }, + "description": "Sample for ListUserWorkloadsConfigMaps", + "file": "composer_v1beta1_generated_environments_list_user_workloads_config_maps_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_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": "composer_v1beta1_generated_environments_list_user_workloads_config_maps_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_user_workloads_config_maps", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListUserWorkloadsConfigMaps", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "ListUserWorkloadsConfigMaps" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsConfigMapsPager", + "shortName": "list_user_workloads_config_maps" + }, + "description": "Sample for ListUserWorkloadsConfigMaps", + "file": "composer_v1beta1_generated_environments_list_user_workloads_config_maps_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_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": "composer_v1beta1_generated_environments_list_user_workloads_config_maps_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.list_user_workloads_secrets", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListUserWorkloadsSecrets", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "ListUserWorkloadsSecrets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsSecretsAsyncPager", + "shortName": "list_user_workloads_secrets" + }, + "description": "Sample for ListUserWorkloadsSecrets", + "file": "composer_v1beta1_generated_environments_list_user_workloads_secrets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_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": "composer_v1beta1_generated_environments_list_user_workloads_secrets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_user_workloads_secrets", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListUserWorkloadsSecrets", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "ListUserWorkloadsSecrets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsSecretsPager", + "shortName": "list_user_workloads_secrets" + }, + "description": "Sample for ListUserWorkloadsSecrets", + "file": "composer_v1beta1_generated_environments_list_user_workloads_secrets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_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": "composer_v1beta1_generated_environments_list_user_workloads_secrets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.list_workloads", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListWorkloads", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "ListWorkloads" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListWorkloadsAsyncPager", + "shortName": "list_workloads" + }, + "description": "Sample for ListWorkloads", + "file": "composer_v1beta1_generated_environments_list_workloads_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_ListWorkloads_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": "composer_v1beta1_generated_environments_list_workloads_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_workloads", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListWorkloads", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "ListWorkloads" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListWorkloadsPager", + "shortName": "list_workloads" + }, + "description": "Sample for ListWorkloads", + "file": "composer_v1beta1_generated_environments_list_workloads_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_ListWorkloads_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": "composer_v1beta1_generated_environments_list_workloads_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.load_snapshot", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.LoadSnapshot", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "LoadSnapshot" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest" + }, + { + "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": "load_snapshot" + }, + "description": "Sample for LoadSnapshot", + "file": "composer_v1beta1_generated_environments_load_snapshot_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_LoadSnapshot_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_load_snapshot_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.load_snapshot", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.LoadSnapshot", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "LoadSnapshot" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest" + }, + { + "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": "load_snapshot" + }, + "description": "Sample for LoadSnapshot", + "file": "composer_v1beta1_generated_environments_load_snapshot_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_LoadSnapshot_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_load_snapshot_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.poll_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.PollAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "PollAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse", + "shortName": "poll_airflow_command" + }, + "description": "Sample for PollAirflowCommand", + "file": "composer_v1beta1_generated_environments_poll_airflow_command_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_PollAirflowCommand_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_poll_airflow_command_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.poll_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.PollAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "PollAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse", + "shortName": "poll_airflow_command" + }, + "description": "Sample for PollAirflowCommand", + "file": "composer_v1beta1_generated_environments_poll_airflow_command_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_PollAirflowCommand_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_poll_airflow_command_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.restart_web_server", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.RestartWebServer", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "RestartWebServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest" + }, + { + "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": "restart_web_server" + }, + "description": "Sample for RestartWebServer", + "file": "composer_v1beta1_generated_environments_restart_web_server_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_RestartWebServer_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_restart_web_server_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.restart_web_server", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.RestartWebServer", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "RestartWebServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest" + }, + { + "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": "restart_web_server" + }, + "description": "Sample for RestartWebServer", + "file": "composer_v1beta1_generated_environments_restart_web_server_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_RestartWebServer_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_restart_web_server_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.save_snapshot", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.SaveSnapshot", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "SaveSnapshot" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest" + }, + { + "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": "save_snapshot" + }, + "description": "Sample for SaveSnapshot", + "file": "composer_v1beta1_generated_environments_save_snapshot_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_SaveSnapshot_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_save_snapshot_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.save_snapshot", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.SaveSnapshot", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "SaveSnapshot" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest" + }, + { + "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": "save_snapshot" + }, + "description": "Sample for SaveSnapshot", + "file": "composer_v1beta1_generated_environments_save_snapshot_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_SaveSnapshot_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_save_snapshot_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.stop_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.StopAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "StopAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse", + "shortName": "stop_airflow_command" + }, + "description": "Sample for StopAirflowCommand", + "file": "composer_v1beta1_generated_environments_stop_airflow_command_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_StopAirflowCommand_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_stop_airflow_command_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.stop_airflow_command", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.StopAirflowCommand", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "StopAirflowCommand" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse", + "shortName": "stop_airflow_command" + }, + "description": "Sample for StopAirflowCommand", + "file": "composer_v1beta1_generated_environments_stop_airflow_command_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_StopAirflowCommand_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_stop_airflow_command_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.update_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateEnvironmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "environment", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.Environment" + }, + { + "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_environment" + }, + "description": "Sample for UpdateEnvironment", + "file": "composer_v1beta1_generated_environments_update_environment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_UpdateEnvironment_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_update_environment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_environment", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateEnvironment", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateEnvironment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateEnvironmentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "environment", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.Environment" + }, + { + "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_environment" + }, + "description": "Sample for UpdateEnvironment", + "file": "composer_v1beta1_generated_environments_update_environment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_UpdateEnvironment_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_update_environment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.update_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsConfigMapRequest" + }, + { + "name": "user_workloads_config_map", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", + "shortName": "update_user_workloads_config_map" + }, + "description": "Sample for UpdateUserWorkloadsConfigMap", + "file": "composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_user_workloads_config_map", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateUserWorkloadsConfigMap", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateUserWorkloadsConfigMap" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsConfigMapRequest" + }, + { + "name": "user_workloads_config_map", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", + "shortName": "update_user_workloads_config_map" + }, + "description": "Sample for UpdateUserWorkloadsConfigMap", + "file": "composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", + "shortName": "EnvironmentsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.update_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsSecretRequest" + }, + { + "name": "user_workloads_secret", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", + "shortName": "update_user_workloads_secret" + }, + "description": "Sample for UpdateUserWorkloadsSecret", + "file": "composer_v1beta1_generated_environments_update_user_workloads_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_update_user_workloads_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", + "shortName": "EnvironmentsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_user_workloads_secret", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateUserWorkloadsSecret", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", + "shortName": "Environments" + }, + "shortName": "UpdateUserWorkloadsSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsSecretRequest" + }, + { + "name": "user_workloads_secret", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", + "shortName": "update_user_workloads_secret" + }, + "description": "Sample for UpdateUserWorkloadsSecret", + "file": "composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.ImageVersionsAsyncClient", + "shortName": "ImageVersionsAsyncClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.ImageVersionsAsyncClient.list_image_versions", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions.ListImageVersions", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "shortName": "ImageVersions" + }, + "shortName": "ListImageVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.services.image_versions.pagers.ListImageVersionsAsyncPager", + "shortName": "list_image_versions" + }, + "description": "Sample for ListImageVersions", + "file": "composer_v1beta1_generated_image_versions_list_image_versions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_ImageVersions_ListImageVersions_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_image_versions_list_image_versions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.ImageVersionsClient", + "shortName": "ImageVersionsClient" + }, + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.ImageVersionsClient.list_image_versions", + "method": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions.ListImageVersions", + "service": { + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", + "shortName": "ImageVersions" + }, + "shortName": "ListImageVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest" + }, + { + "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.orchestration.airflow.service_v1beta1.services.image_versions.pagers.ListImageVersionsPager", + "shortName": "list_image_versions" + }, + "description": "Sample for ListImageVersions", + "file": "composer_v1beta1_generated_image_versions_list_image_versions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "composer_v1beta1_generated_ImageVersions_ListImageVersions_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "composer_v1beta1_generated_image_versions_list_image_versions_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py new file mode 100644 index 000000000000..14f61f63b516 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py @@ -0,0 +1,201 @@ +#! /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 serviceCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'check_upgrade': ('environment', 'image_version', ), + 'create_environment': ('parent', 'environment', ), + 'create_user_workloads_config_map': ('parent', 'user_workloads_config_map', ), + 'create_user_workloads_secret': ('parent', 'user_workloads_secret', ), + 'database_failover': ('environment', ), + 'delete_environment': ('name', ), + 'delete_user_workloads_config_map': ('name', ), + 'delete_user_workloads_secret': ('name', ), + 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), + 'fetch_database_properties': ('environment', ), + 'get_environment': ('name', ), + 'get_user_workloads_config_map': ('name', ), + 'get_user_workloads_secret': ('name', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), + 'list_user_workloads_config_maps': ('parent', 'page_size', 'page_token', ), + 'list_user_workloads_secrets': ('parent', 'page_size', 'page_token', ), + 'list_workloads': ('parent', 'page_size', 'page_token', 'filter', ), + 'load_snapshot': ('environment', 'snapshot_path', 'skip_pypi_packages_installation', 'skip_environment_variables_setting', 'skip_airflow_overrides_setting', 'skip_gcs_data_copying', ), + 'poll_airflow_command': ('environment', 'execution_id', 'pod', 'pod_namespace', 'next_line_number', ), + 'restart_web_server': ('name', ), + 'save_snapshot': ('environment', 'snapshot_location', ), + 'stop_airflow_command': ('environment', 'execution_id', 'pod', 'pod_namespace', 'force', ), + 'update_environment': ('update_mask', 'name', 'environment', ), + 'update_user_workloads_config_map': ('user_workloads_config_map', ), + 'update_user_workloads_secret': ('user_workloads_secret', ), + } + + 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=serviceCallTransformer(), +): + """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 service 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-orchestration-airflow/v1beta1/setup.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/setup.py new file mode 100644 index 000000000000..2e2dec3073ba --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow-service' + + +description = "Google Cloud Orchestration Airflow Service API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/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.0,!=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.0,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0", + "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", + "protobuf>=3.20.2,<7.0.0,!=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-orchestration-airflow-service" + +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-orchestration-airflow/v1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a77f12bc13e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# 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-orchestration-airflow/v1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/__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-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py new file mode 100644 index 000000000000..80fe2db8e672 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py @@ -0,0 +1,17816 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.orchestration.airflow.service_v1beta1.services.environments import EnvironmentsAsyncClient +from google.cloud.orchestration.airflow.service_v1beta1.services.environments import EnvironmentsClient +from google.cloud.orchestration.airflow.service_v1beta1.services.environments import pagers +from google.cloud.orchestration.airflow.service_v1beta1.services.environments import transports +from google.cloud.orchestration.airflow.service_v1beta1.types import environments +from google.cloud.orchestration.airflow.service_v1beta1.types import operations +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 + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +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 EnvironmentsClient._get_default_mtls_endpoint(None) is None + assert EnvironmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EnvironmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EnvironmentsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + EnvironmentsClient._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 EnvironmentsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert EnvironmentsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + EnvironmentsClient._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 EnvironmentsClient._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 EnvironmentsClient._get_client_cert_source(None, False) is None + assert EnvironmentsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert EnvironmentsClient._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 EnvironmentsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert EnvironmentsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = EnvironmentsClient._DEFAULT_UNIVERSE + default_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert EnvironmentsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert EnvironmentsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "always") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + assert EnvironmentsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + assert EnvironmentsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + EnvironmentsClient._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 EnvironmentsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert EnvironmentsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert EnvironmentsClient._get_universe_domain(None, None) == EnvironmentsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + EnvironmentsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = EnvironmentsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = EnvironmentsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (EnvironmentsClient, "grpc"), + (EnvironmentsAsyncClient, "grpc_asyncio"), + (EnvironmentsClient, "rest"), +]) +def test_environments_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 == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://composer.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EnvironmentsGrpcTransport, "grpc"), + (transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EnvironmentsRestTransport, "rest"), +]) +def test_environments_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", [ + (EnvironmentsClient, "grpc"), + (EnvironmentsAsyncClient, "grpc_asyncio"), + (EnvironmentsClient, "rest"), +]) +def test_environments_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 == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://composer.googleapis.com' + ) + + +def test_environments_client_get_transport_class(): + transport = EnvironmentsClient.get_transport_class() + available_transports = [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsRestTransport, + ] + assert transport in available_transports + + transport = EnvironmentsClient.get_transport_class("grpc") + assert transport == transports.EnvironmentsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), +]) +@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) +def test_environments_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(EnvironmentsClient, '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(EnvironmentsClient, '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", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "true"), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "false"), +]) +@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_environments_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", [ + EnvironmentsClient, EnvironmentsAsyncClient +]) +@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) +def test_environments_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", [ + EnvironmentsClient, EnvironmentsAsyncClient +]) +@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) +def test_environments_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = EnvironmentsClient._DEFAULT_UNIVERSE + default_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EnvironmentsClient._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", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), +]) +def test_environments_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", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", None), +]) +def test_environments_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_environments_client_client_options_from_dict(): + with mock.patch('google.cloud.orchestration.airflow.service_v1beta1.services.environments.transports.EnvironmentsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EnvironmentsClient( + 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", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_environments_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( + "composer.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="composer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateEnvironmentRequest, + dict, +]) +def test_create_environment(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.CreateEnvironmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_environment_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 = EnvironmentsClient( + 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 = environments.CreateEnvironmentRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_environment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateEnvironmentRequest( + parent='parent_value', + ) + +def test_create_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + request = {} + client.create_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( + 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_environment 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_environment] = mock_rpc + + request = {} + await client.create_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.CreateEnvironmentRequest): + client = EnvironmentsAsyncClient( + 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_environment), + '__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_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.CreateEnvironmentRequest() + 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_environment_async_from_dict(): + await test_create_environment_async(request_type=dict) + +def test_create_environment_field_headers(): + client = EnvironmentsClient( + 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 = environments.CreateEnvironmentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_environment(request) + + # Establish that the 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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.CreateEnvironmentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_environment(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_environment_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__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_environment( + parent='parent_value', + environment=environments.Environment(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].environment + mock_val = environments.Environment(name='name_value') + assert arg == mock_val + + +def test_create_environment_flattened_error(): + client = EnvironmentsClient( + 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_environment( + environments.CreateEnvironmentRequest(), + parent='parent_value', + environment=environments.Environment(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_environment_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__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_environment( + parent='parent_value', + environment=environments.Environment(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].environment + mock_val = environments.Environment(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_environment_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_environment( + environments.CreateEnvironmentRequest(), + parent='parent_value', + environment=environments.Environment(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetEnvironmentRequest, + dict, +]) +def test_get_environment(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.Environment( + name='name_value', + uuid='uuid_value', + state=environments.Environment.State.CREATING, + satisfies_pzs=True, + satisfies_pzi=True, + ) + response = client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.GetEnvironmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.Environment) + assert response.name == 'name_value' + assert response.uuid == 'uuid_value' + assert response.state == environments.Environment.State.CREATING + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +def test_get_environment_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 = EnvironmentsClient( + 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 = environments.GetEnvironmentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_environment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetEnvironmentRequest( + name='name_value', + ) + +def test_get_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + request = {} + client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_environment(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_environment_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 = EnvironmentsAsyncClient( + 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_environment 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_environment] = mock_rpc + + request = {} + await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.GetEnvironmentRequest): + client = EnvironmentsAsyncClient( + 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment( + name='name_value', + uuid='uuid_value', + state=environments.Environment.State.CREATING, + satisfies_pzs=True, + satisfies_pzi=True, + )) + response = await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.GetEnvironmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.Environment) + assert response.name == 'name_value' + assert response.uuid == 'uuid_value' + assert response.state == environments.Environment.State.CREATING + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.asyncio +async def test_get_environment_async_from_dict(): + await test_get_environment_async(request_type=dict) + +def test_get_environment_field_headers(): + client = EnvironmentsClient( + 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 = environments.GetEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value = environments.Environment() + client.get_environment(request) + + # Establish that the 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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.GetEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment()) + await client.get_environment(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_environment_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.Environment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_environment( + 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_environment_flattened_error(): + client = EnvironmentsClient( + 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_environment( + environments.GetEnvironmentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_environment_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.Environment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_environment( + 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_environment_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_environment( + environments.GetEnvironmentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListEnvironmentsRequest, + dict, +]) +def test_list_environments(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListEnvironmentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.ListEnvironmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnvironmentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_environments_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 = EnvironmentsClient( + 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 = environments.ListEnvironmentsRequest( + 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_environments), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_environments(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListEnvironmentsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_environments_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 = EnvironmentsClient( + 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_environments 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_environments] = mock_rpc + request = {} + client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_environments(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_environments_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 = EnvironmentsAsyncClient( + 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_environments 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_environments] = mock_rpc + + request = {} + await client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_environments(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_environments_async(transport: str = 'grpc_asyncio', request_type=environments.ListEnvironmentsRequest): + client = EnvironmentsAsyncClient( + 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_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.ListEnvironmentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnvironmentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_environments_async_from_dict(): + await test_list_environments_async(request_type=dict) + +def test_list_environments_field_headers(): + client = EnvironmentsClient( + 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 = environments.ListEnvironmentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value = environments.ListEnvironmentsResponse() + client.list_environments(request) + + # Establish that the 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_environments_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.ListEnvironmentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse()) + await client.list_environments(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_environments_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListEnvironmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_environments( + 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_environments_flattened_error(): + client = EnvironmentsClient( + 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_environments( + environments.ListEnvironmentsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_environments_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListEnvironmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_environments( + 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_environments_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_environments( + environments.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +def test_list_environments_pager(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_environments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + environments.Environment(), + ], + next_page_token='abc', + ), + environments.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + ], + next_page_token='ghi', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_environments(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, environments.Environment) + for i in results) +def test_list_environments_pages(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_environments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + environments.Environment(), + ], + next_page_token='abc', + ), + environments.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + ], + next_page_token='ghi', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_environments(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_environments_async_pager(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + environments.Environment(), + ], + next_page_token='abc', + ), + environments.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + ], + next_page_token='ghi', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_environments(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, environments.Environment) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_environments_async_pages(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + environments.Environment(), + ], + next_page_token='abc', + ), + environments.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + ], + next_page_token='ghi', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + ], + ), + 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_environments(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", [ + environments.UpdateEnvironmentRequest, + dict, +]) +def test_update_environment(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.UpdateEnvironmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_environment_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 = EnvironmentsClient( + 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 = environments.UpdateEnvironmentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_environment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateEnvironmentRequest( + name='name_value', + ) + +def test_update_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + request = {} + client.update_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( + 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_environment 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_environment] = mock_rpc + + request = {} + await client.update_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateEnvironmentRequest): + client = EnvironmentsAsyncClient( + 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_environment), + '__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_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.UpdateEnvironmentRequest() + 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_environment_async_from_dict(): + await test_update_environment_async(request_type=dict) + +def test_update_environment_field_headers(): + client = EnvironmentsClient( + 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 = environments.UpdateEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.UpdateEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_update_environment_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__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_environment( + name='name_value', + environment=environments.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].environment + mock_val = environments.Environment(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_environment_flattened_error(): + client = EnvironmentsClient( + 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_environment( + environments.UpdateEnvironmentRequest(), + name='name_value', + environment=environments.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_environment_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__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_environment( + name='name_value', + environment=environments.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].environment + mock_val = environments.Environment(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_environment_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_environment( + environments.UpdateEnvironmentRequest(), + name='name_value', + environment=environments.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteEnvironmentRequest, + dict, +]) +def test_delete_environment(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.DeleteEnvironmentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_environment_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 = EnvironmentsClient( + 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 = environments.DeleteEnvironmentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_environment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteEnvironmentRequest( + name='name_value', + ) + +def test_delete_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + request = {} + client.delete_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( + 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_environment 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_environment] = mock_rpc + + request = {} + await client.delete_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteEnvironmentRequest): + client = EnvironmentsAsyncClient( + 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_environment), + '__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_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.DeleteEnvironmentRequest() + 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_environment_async_from_dict(): + await test_delete_environment_async(request_type=dict) + +def test_delete_environment_field_headers(): + client = EnvironmentsClient( + 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 = environments.DeleteEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_environment(request) + + # Establish that the 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_environment_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.DeleteEnvironmentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_environment(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_environment_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__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_environment( + 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_environment_flattened_error(): + client = EnvironmentsClient( + 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_environment( + environments.DeleteEnvironmentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_environment_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__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_environment( + 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_environment_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_environment( + environments.DeleteEnvironmentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.RestartWebServerRequest, + dict, +]) +def test_restart_web_server(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.restart_web_server), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.restart_web_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.RestartWebServerRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restart_web_server_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 = EnvironmentsClient( + 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 = environments.RestartWebServerRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_web_server), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.restart_web_server(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.RestartWebServerRequest( + name='name_value', + ) + +def test_restart_web_server_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 = EnvironmentsClient( + 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.restart_web_server 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.restart_web_server] = mock_rpc + request = {} + client.restart_web_server(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.restart_web_server(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_restart_web_server_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 = EnvironmentsAsyncClient( + 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.restart_web_server 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.restart_web_server] = mock_rpc + + request = {} + await client.restart_web_server(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.restart_web_server(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_restart_web_server_async(transport: str = 'grpc_asyncio', request_type=environments.RestartWebServerRequest): + client = EnvironmentsAsyncClient( + 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.restart_web_server), + '__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.restart_web_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.RestartWebServerRequest() + 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_restart_web_server_async_from_dict(): + await test_restart_web_server_async(request_type=dict) + +def test_restart_web_server_field_headers(): + client = EnvironmentsClient( + 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 = environments.RestartWebServerRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_web_server), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restart_web_server(request) + + # Establish that the 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_restart_web_server_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.RestartWebServerRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restart_web_server), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.restart_web_server(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.CheckUpgradeRequest, + dict, +]) +def test_check_upgrade(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.check_upgrade), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.check_upgrade(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.CheckUpgradeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_check_upgrade_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 = EnvironmentsClient( + 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 = environments.CheckUpgradeRequest( + environment='environment_value', + image_version='image_version_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.check_upgrade(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CheckUpgradeRequest( + environment='environment_value', + image_version='image_version_value', + ) + +def test_check_upgrade_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 = EnvironmentsClient( + 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.check_upgrade 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.check_upgrade] = mock_rpc + request = {} + client.check_upgrade(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.check_upgrade(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_check_upgrade_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 = EnvironmentsAsyncClient( + 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.check_upgrade 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.check_upgrade] = mock_rpc + + request = {} + await client.check_upgrade(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.check_upgrade(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_check_upgrade_async(transport: str = 'grpc_asyncio', request_type=environments.CheckUpgradeRequest): + client = EnvironmentsAsyncClient( + 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.check_upgrade), + '__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.check_upgrade(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.CheckUpgradeRequest() + 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_check_upgrade_async_from_dict(): + await test_check_upgrade_async(request_type=dict) + +def test_check_upgrade_field_headers(): + client = EnvironmentsClient( + 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 = environments.CheckUpgradeRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.check_upgrade(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_check_upgrade_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.CheckUpgradeRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.check_upgrade(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.ExecuteAirflowCommandRequest, + dict, +]) +def test_execute_airflow_command(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.execute_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ExecuteAirflowCommandResponse( + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + error='error_value', + ) + response = client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.ExecuteAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.ExecuteAirflowCommandResponse) + assert response.execution_id == 'execution_id_value' + assert response.pod == 'pod_value' + assert response.pod_namespace == 'pod_namespace_value' + assert response.error == 'error_value' + + +def test_execute_airflow_command_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 = EnvironmentsClient( + 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 = environments.ExecuteAirflowCommandRequest( + environment='environment_value', + command='command_value', + subcommand='subcommand_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.execute_airflow_command(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ExecuteAirflowCommandRequest( + environment='environment_value', + command='command_value', + subcommand='subcommand_value', + ) + +def test_execute_airflow_command_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 = EnvironmentsClient( + 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc + request = {} + client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.execute_airflow_command(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_execute_airflow_command_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 = EnvironmentsAsyncClient( + 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc + + request = {} + await client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.execute_airflow_command(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_execute_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.ExecuteAirflowCommandRequest): + client = EnvironmentsAsyncClient( + 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.execute_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse( + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + error='error_value', + )) + response = await client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.ExecuteAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.ExecuteAirflowCommandResponse) + assert response.execution_id == 'execution_id_value' + assert response.pod == 'pod_value' + assert response.pod_namespace == 'pod_namespace_value' + assert response.error == 'error_value' + + +@pytest.mark.asyncio +async def test_execute_airflow_command_async_from_dict(): + await test_execute_airflow_command_async(request_type=dict) + +def test_execute_airflow_command_field_headers(): + client = EnvironmentsClient( + 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 = environments.ExecuteAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + call.return_value = environments.ExecuteAirflowCommandResponse() + client.execute_airflow_command(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_execute_airflow_command_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.ExecuteAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse()) + await client.execute_airflow_command(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.StopAirflowCommandRequest, + dict, +]) +def test_stop_airflow_command(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.stop_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.StopAirflowCommandResponse( + is_done=True, + output=['output_value'], + ) + response = client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.StopAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ['output_value'] + + +def test_stop_airflow_command_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 = EnvironmentsClient( + 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 = environments.StopAirflowCommandRequest( + environment='environment_value', + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.stop_airflow_command(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.StopAirflowCommandRequest( + environment='environment_value', + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + ) + +def test_stop_airflow_command_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 = EnvironmentsClient( + 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc + request = {} + client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stop_airflow_command(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_stop_airflow_command_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 = EnvironmentsAsyncClient( + 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc + + request = {} + await client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.stop_airflow_command(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_stop_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.StopAirflowCommandRequest): + client = EnvironmentsAsyncClient( + 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.stop_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse( + is_done=True, + output=['output_value'], + )) + response = await client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.StopAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ['output_value'] + + +@pytest.mark.asyncio +async def test_stop_airflow_command_async_from_dict(): + await test_stop_airflow_command_async(request_type=dict) + +def test_stop_airflow_command_field_headers(): + client = EnvironmentsClient( + 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 = environments.StopAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + call.return_value = environments.StopAirflowCommandResponse() + client.stop_airflow_command(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_stop_airflow_command_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.StopAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse()) + await client.stop_airflow_command(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.PollAirflowCommandRequest, + dict, +]) +def test_poll_airflow_command(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.poll_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.PollAirflowCommandResponse( + output_end=True, + ) + response = client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.PollAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.PollAirflowCommandResponse) + assert response.output_end is True + + +def test_poll_airflow_command_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 = EnvironmentsClient( + 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 = environments.PollAirflowCommandRequest( + environment='environment_value', + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.poll_airflow_command(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.PollAirflowCommandRequest( + environment='environment_value', + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + ) + +def test_poll_airflow_command_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 = EnvironmentsClient( + 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc + request = {} + client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.poll_airflow_command(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_poll_airflow_command_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 = EnvironmentsAsyncClient( + 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc + + request = {} + await client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.poll_airflow_command(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_poll_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.PollAirflowCommandRequest): + client = EnvironmentsAsyncClient( + 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.poll_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse( + output_end=True, + )) + response = await client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.PollAirflowCommandRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.PollAirflowCommandResponse) + assert response.output_end is True + + +@pytest.mark.asyncio +async def test_poll_airflow_command_async_from_dict(): + await test_poll_airflow_command_async(request_type=dict) + +def test_poll_airflow_command_field_headers(): + client = EnvironmentsClient( + 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 = environments.PollAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + call.return_value = environments.PollAirflowCommandResponse() + client.poll_airflow_command(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_poll_airflow_command_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.PollAirflowCommandRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse()) + await client.poll_airflow_command(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.ListWorkloadsRequest, + dict, +]) +def test_list_workloads(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_workloads), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListWorkloadsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.ListWorkloadsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_workloads_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 = EnvironmentsClient( + 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 = environments.ListWorkloadsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workloads(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListWorkloadsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_workloads_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 = EnvironmentsClient( + 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_workloads 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_workloads] = mock_rpc + request = {} + client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workloads(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_workloads_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 = EnvironmentsAsyncClient( + 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_workloads 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_workloads] = mock_rpc + + request = {} + await client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_workloads(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_workloads_async(transport: str = 'grpc_asyncio', request_type=environments.ListWorkloadsRequest): + client = EnvironmentsAsyncClient( + 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_workloads), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.ListWorkloadsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_workloads_async_from_dict(): + await test_list_workloads_async(request_type=dict) + +def test_list_workloads_field_headers(): + client = EnvironmentsClient( + 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 = environments.ListWorkloadsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + call.return_value = environments.ListWorkloadsResponse() + client.list_workloads(request) + + # Establish that the 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_workloads_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.ListWorkloadsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse()) + await client.list_workloads(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_workloads_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListWorkloadsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workloads( + 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_workloads_flattened_error(): + client = EnvironmentsClient( + 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_workloads( + environments.ListWorkloadsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_workloads_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListWorkloadsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workloads( + 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_workloads_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_workloads( + environments.ListWorkloadsRequest(), + parent='parent_value', + ) + + +def test_list_workloads_pager(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_workloads), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='abc', + ), + environments.ListWorkloadsResponse( + workloads=[], + next_page_token='def', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='ghi', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workloads(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, environments.ListWorkloadsResponse.ComposerWorkload) + for i in results) +def test_list_workloads_pages(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_workloads), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='abc', + ), + environments.ListWorkloadsResponse( + workloads=[], + next_page_token='def', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='ghi', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workloads(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_workloads_async_pager(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='abc', + ), + environments.ListWorkloadsResponse( + workloads=[], + next_page_token='def', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='ghi', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workloads(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, environments.ListWorkloadsResponse.ComposerWorkload) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_workloads_async_pages(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='abc', + ), + environments.ListWorkloadsResponse( + workloads=[], + next_page_token='def', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='ghi', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + ), + 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_workloads(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", [ + environments.CreateUserWorkloadsSecretRequest, + dict, +]) +def test_create_user_workloads_secret(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret( + name='name_value', + ) + response = client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.CreateUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +def test_create_user_workloads_secret_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 = EnvironmentsClient( + 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 = environments.CreateUserWorkloadsSecretRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_user_workloads_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsSecretRequest( + parent='parent_value', + ) + +def test_create_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + request = {} + client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + await client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.CreateUserWorkloadsSecretRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + response = await client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.CreateUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_user_workloads_secret_async_from_dict(): + await test_create_user_workloads_secret_async(request_type=dict) + +def test_create_user_workloads_secret_field_headers(): + client = EnvironmentsClient( + 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 = environments.CreateUserWorkloadsSecretRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.create_user_workloads_secret(request) + + # Establish that the 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_user_workloads_secret_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.CreateUserWorkloadsSecretRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + await client.create_user_workloads_secret(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_user_workloads_secret_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user_workloads_secret( + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_workloads_secret + mock_val = environments.UserWorkloadsSecret(name='name_value') + assert arg == mock_val + + +def test_create_user_workloads_secret_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.CreateUserWorkloadsSecretRequest(), + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_user_workloads_secret_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user_workloads_secret( + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_workloads_secret + mock_val = environments.UserWorkloadsSecret(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_user_workloads_secret_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret( + environments.CreateUserWorkloadsSecretRequest(), + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsSecretRequest, + dict, +]) +def test_get_user_workloads_secret(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret( + name='name_value', + ) + response = client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.GetUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +def test_get_user_workloads_secret_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 = EnvironmentsClient( + 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 = environments.GetUserWorkloadsSecretRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_user_workloads_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsSecretRequest( + name='name_value', + ) + +def test_get_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + request = {} + client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + await client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.GetUserWorkloadsSecretRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + response = await client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.GetUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_user_workloads_secret_async_from_dict(): + await test_get_user_workloads_secret_async(request_type=dict) + +def test_get_user_workloads_secret_field_headers(): + client = EnvironmentsClient( + 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 = environments.GetUserWorkloadsSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.get_user_workloads_secret(request) + + # Establish that the 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_user_workloads_secret_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.GetUserWorkloadsSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + await client.get_user_workloads_secret(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_user_workloads_secret_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user_workloads_secret( + 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_user_workloads_secret_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.GetUserWorkloadsSecretRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_user_workloads_secret_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user_workloads_secret( + 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_user_workloads_secret_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret( + environments.GetUserWorkloadsSecretRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsSecretsRequest, + dict, +]) +def test_list_user_workloads_secrets(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsSecretsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.ListUserWorkloadsSecretsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsSecretsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_user_workloads_secrets_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 = EnvironmentsClient( + 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 = environments.ListUserWorkloadsSecretsRequest( + 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_user_workloads_secrets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_user_workloads_secrets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsSecretsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_user_workloads_secrets_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 = EnvironmentsClient( + 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc + request = {} + client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_user_workloads_secrets(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_user_workloads_secrets_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 = EnvironmentsAsyncClient( + 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc + + request = {} + await client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_user_workloads_secrets(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_user_workloads_secrets_async(transport: str = 'grpc_asyncio', request_type=environments.ListUserWorkloadsSecretsRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.ListUserWorkloadsSecretsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsSecretsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_user_workloads_secrets_async_from_dict(): + await test_list_user_workloads_secrets_async(request_type=dict) + +def test_list_user_workloads_secrets_field_headers(): + client = EnvironmentsClient( + 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 = environments.ListUserWorkloadsSecretsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + call.return_value = environments.ListUserWorkloadsSecretsResponse() + client.list_user_workloads_secrets(request) + + # Establish that the 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_user_workloads_secrets_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.ListUserWorkloadsSecretsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse()) + await client.list_user_workloads_secrets(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_user_workloads_secrets_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsSecretsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_user_workloads_secrets( + 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_user_workloads_secrets_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_secrets( + environments.ListUserWorkloadsSecretsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_user_workloads_secrets_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsSecretsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_user_workloads_secrets( + 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_user_workloads_secrets_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_secrets( + environments.ListUserWorkloadsSecretsRequest(), + parent='parent_value', + ) + + +def test_list_user_workloads_secrets_pager(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_user_workloads_secrets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[], + next_page_token='def', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_user_workloads_secrets(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, environments.UserWorkloadsSecret) + for i in results) +def test_list_user_workloads_secrets_pages(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_user_workloads_secrets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[], + next_page_token='def', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + ), + RuntimeError, + ) + pages = list(client.list_user_workloads_secrets(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_user_workloads_secrets_async_pager(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[], + next_page_token='def', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_user_workloads_secrets(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, environments.UserWorkloadsSecret) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_user_workloads_secrets_async_pages(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[], + next_page_token='def', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + ), + 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_user_workloads_secrets(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", [ + environments.UpdateUserWorkloadsSecretRequest, + dict, +]) +def test_update_user_workloads_secret(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret( + name='name_value', + ) + response = client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.UpdateUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +def test_update_user_workloads_secret_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 = EnvironmentsClient( + 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 = environments.UpdateUserWorkloadsSecretRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_user_workloads_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsSecretRequest( + ) + +def test_update_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + request = {} + client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + await client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateUserWorkloadsSecretRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + response = await client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.UpdateUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_user_workloads_secret_async_from_dict(): + await test_update_user_workloads_secret_async(request_type=dict) + +def test_update_user_workloads_secret_field_headers(): + client = EnvironmentsClient( + 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 = environments.UpdateUserWorkloadsSecretRequest() + + request.user_workloads_secret.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.update_user_workloads_secret(request) + + # Establish that the 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', + 'user_workloads_secret.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_user_workloads_secret_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.UpdateUserWorkloadsSecretRequest() + + request.user_workloads_secret.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + await client.update_user_workloads_secret(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', + 'user_workloads_secret.name=name_value', + ) in kw['metadata'] + + +def test_update_user_workloads_secret_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user_workloads_secret( + user_workloads_secret=environments.UserWorkloadsSecret(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].user_workloads_secret + mock_val = environments.UserWorkloadsSecret(name='name_value') + assert arg == mock_val + + +def test_update_user_workloads_secret_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.UpdateUserWorkloadsSecretRequest(), + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_user_workloads_secret_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user_workloads_secret( + user_workloads_secret=environments.UserWorkloadsSecret(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].user_workloads_secret + mock_val = environments.UserWorkloadsSecret(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_user_workloads_secret_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret( + environments.UpdateUserWorkloadsSecretRequest(), + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsSecretRequest, + dict, +]) +def test_delete_user_workloads_secret(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.DeleteUserWorkloadsSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_workloads_secret_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 = EnvironmentsClient( + 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 = environments.DeleteUserWorkloadsSecretRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_user_workloads_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsSecretRequest( + name='name_value', + ) + +def test_delete_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + request = {} + client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + await client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteUserWorkloadsSecretRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.DeleteUserWorkloadsSecretRequest() + 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_user_workloads_secret_async_from_dict(): + await test_delete_user_workloads_secret_async(request_type=dict) + +def test_delete_user_workloads_secret_field_headers(): + client = EnvironmentsClient( + 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 = environments.DeleteUserWorkloadsSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + call.return_value = None + client.delete_user_workloads_secret(request) + + # Establish that the 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_user_workloads_secret_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.DeleteUserWorkloadsSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_workloads_secret(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_user_workloads_secret_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user_workloads_secret( + 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_user_workloads_secret_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.DeleteUserWorkloadsSecretRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_user_workloads_secret_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user_workloads_secret( + 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_user_workloads_secret_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_secret( + environments.DeleteUserWorkloadsSecretRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsConfigMapRequest, + dict, +]) +def test_create_user_workloads_config_map(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap( + name='name_value', + ) + response = client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.CreateUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +def test_create_user_workloads_config_map_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 = EnvironmentsClient( + 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 = environments.CreateUserWorkloadsConfigMapRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_user_workloads_config_map(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsConfigMapRequest( + parent='parent_value', + ) + +def test_create_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + request = {} + client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + await client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.CreateUserWorkloadsConfigMapRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + response = await client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.CreateUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_user_workloads_config_map_async_from_dict(): + await test_create_user_workloads_config_map_async(request_type=dict) + +def test_create_user_workloads_config_map_field_headers(): + client = EnvironmentsClient( + 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 = environments.CreateUserWorkloadsConfigMapRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.create_user_workloads_config_map(request) + + # Establish that the 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_user_workloads_config_map_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.CreateUserWorkloadsConfigMapRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + await client.create_user_workloads_config_map(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_user_workloads_config_map_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user_workloads_config_map( + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_workloads_config_map + mock_val = environments.UserWorkloadsConfigMap(name='name_value') + assert arg == mock_val + + +def test_create_user_workloads_config_map_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.CreateUserWorkloadsConfigMapRequest(), + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_user_workloads_config_map_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user_workloads_config_map( + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_workloads_config_map + mock_val = environments.UserWorkloadsConfigMap(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_user_workloads_config_map_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map( + environments.CreateUserWorkloadsConfigMapRequest(), + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsConfigMapRequest, + dict, +]) +def test_get_user_workloads_config_map(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap( + name='name_value', + ) + response = client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.GetUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +def test_get_user_workloads_config_map_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 = EnvironmentsClient( + 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 = environments.GetUserWorkloadsConfigMapRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_user_workloads_config_map(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsConfigMapRequest( + name='name_value', + ) + +def test_get_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + request = {} + client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + await client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.GetUserWorkloadsConfigMapRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + response = await client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.GetUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_user_workloads_config_map_async_from_dict(): + await test_get_user_workloads_config_map_async(request_type=dict) + +def test_get_user_workloads_config_map_field_headers(): + client = EnvironmentsClient( + 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 = environments.GetUserWorkloadsConfigMapRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.get_user_workloads_config_map(request) + + # Establish that the 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_user_workloads_config_map_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.GetUserWorkloadsConfigMapRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + await client.get_user_workloads_config_map(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_user_workloads_config_map_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user_workloads_config_map( + 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_user_workloads_config_map_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.GetUserWorkloadsConfigMapRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_user_workloads_config_map_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user_workloads_config_map( + 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_user_workloads_config_map_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map( + environments.GetUserWorkloadsConfigMapRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsConfigMapsRequest, + dict, +]) +def test_list_user_workloads_config_maps(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_config_maps), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsConfigMapsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.ListUserWorkloadsConfigMapsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsConfigMapsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_user_workloads_config_maps_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 = EnvironmentsClient( + 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 = environments.ListUserWorkloadsConfigMapsRequest( + 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_user_workloads_config_maps), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_user_workloads_config_maps(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsConfigMapsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_user_workloads_config_maps_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 = EnvironmentsClient( + 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc + request = {} + client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_user_workloads_config_maps(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_user_workloads_config_maps_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 = EnvironmentsAsyncClient( + 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc + + request = {} + await client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_user_workloads_config_maps(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_user_workloads_config_maps_async(transport: str = 'grpc_asyncio', request_type=environments.ListUserWorkloadsConfigMapsRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_maps), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.ListUserWorkloadsConfigMapsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsConfigMapsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_user_workloads_config_maps_async_from_dict(): + await test_list_user_workloads_config_maps_async(request_type=dict) + +def test_list_user_workloads_config_maps_field_headers(): + client = EnvironmentsClient( + 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 = environments.ListUserWorkloadsConfigMapsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + call.return_value = environments.ListUserWorkloadsConfigMapsResponse() + client.list_user_workloads_config_maps(request) + + # Establish that the 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_user_workloads_config_maps_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.ListUserWorkloadsConfigMapsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse()) + await client.list_user_workloads_config_maps(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_user_workloads_config_maps_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsConfigMapsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_user_workloads_config_maps( + 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_user_workloads_config_maps_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_config_maps( + environments.ListUserWorkloadsConfigMapsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_user_workloads_config_maps_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.ListUserWorkloadsConfigMapsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_user_workloads_config_maps( + 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_user_workloads_config_maps_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_maps( + environments.ListUserWorkloadsConfigMapsRequest(), + parent='parent_value', + ) + + +def test_list_user_workloads_config_maps_pager(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_user_workloads_config_maps), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[], + next_page_token='def', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_user_workloads_config_maps(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, environments.UserWorkloadsConfigMap) + for i in results) +def test_list_user_workloads_config_maps_pages(transport_name: str = "grpc"): + client = EnvironmentsClient( + 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_user_workloads_config_maps), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[], + next_page_token='def', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + ), + RuntimeError, + ) + pages = list(client.list_user_workloads_config_maps(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_user_workloads_config_maps_async_pager(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[], + next_page_token='def', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_user_workloads_config_maps(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, environments.UserWorkloadsConfigMap) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_user_workloads_config_maps_async_pages(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[], + next_page_token='def', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + ), + 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_user_workloads_config_maps(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", [ + environments.UpdateUserWorkloadsConfigMapRequest, + dict, +]) +def test_update_user_workloads_config_map(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap( + name='name_value', + ) + response = client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.UpdateUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +def test_update_user_workloads_config_map_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 = EnvironmentsClient( + 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 = environments.UpdateUserWorkloadsConfigMapRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_user_workloads_config_map(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest( + ) + +def test_update_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + request = {} + client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + await client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateUserWorkloadsConfigMapRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + response = await client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.UpdateUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_user_workloads_config_map_async_from_dict(): + await test_update_user_workloads_config_map_async(request_type=dict) + +def test_update_user_workloads_config_map_field_headers(): + client = EnvironmentsClient( + 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 = environments.UpdateUserWorkloadsConfigMapRequest() + + request.user_workloads_config_map.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.update_user_workloads_config_map(request) + + # Establish that the 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', + 'user_workloads_config_map.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_user_workloads_config_map_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.UpdateUserWorkloadsConfigMapRequest() + + request.user_workloads_config_map.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + await client.update_user_workloads_config_map(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', + 'user_workloads_config_map.name=name_value', + ) in kw['metadata'] + + +def test_update_user_workloads_config_map_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user_workloads_config_map( + user_workloads_config_map=environments.UserWorkloadsConfigMap(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].user_workloads_config_map + mock_val = environments.UserWorkloadsConfigMap(name='name_value') + assert arg == mock_val + + +def test_update_user_workloads_config_map_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.UpdateUserWorkloadsConfigMapRequest(), + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_user_workloads_config_map_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.UserWorkloadsConfigMap() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user_workloads_config_map( + user_workloads_config_map=environments.UserWorkloadsConfigMap(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].user_workloads_config_map + mock_val = environments.UserWorkloadsConfigMap(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_user_workloads_config_map_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map( + environments.UpdateUserWorkloadsConfigMapRequest(), + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsConfigMapRequest, + dict, +]) +def test_delete_user_workloads_config_map(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.DeleteUserWorkloadsConfigMapRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_workloads_config_map_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 = EnvironmentsClient( + 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 = environments.DeleteUserWorkloadsConfigMapRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_user_workloads_config_map(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest( + name='name_value', + ) + +def test_delete_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + request = {} + client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + await client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteUserWorkloadsConfigMapRequest): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.DeleteUserWorkloadsConfigMapRequest() + 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_user_workloads_config_map_async_from_dict(): + await test_delete_user_workloads_config_map_async(request_type=dict) + +def test_delete_user_workloads_config_map_field_headers(): + client = EnvironmentsClient( + 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 = environments.DeleteUserWorkloadsConfigMapRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + call.return_value = None + client.delete_user_workloads_config_map(request) + + # Establish that the 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_user_workloads_config_map_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.DeleteUserWorkloadsConfigMapRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_workloads_config_map(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_user_workloads_config_map_flattened(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user_workloads_config_map( + 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_user_workloads_config_map_flattened_error(): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.DeleteUserWorkloadsConfigMapRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_user_workloads_config_map_flattened_async(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user_workloads_config_map( + 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_user_workloads_config_map_flattened_error_async(): + client = EnvironmentsAsyncClient( + 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_user_workloads_config_map( + environments.DeleteUserWorkloadsConfigMapRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + environments.SaveSnapshotRequest, + dict, +]) +def test_save_snapshot(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.save_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.save_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.SaveSnapshotRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_save_snapshot_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 = EnvironmentsClient( + 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 = environments.SaveSnapshotRequest( + environment='environment_value', + snapshot_location='snapshot_location_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.save_snapshot(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.SaveSnapshotRequest( + environment='environment_value', + snapshot_location='snapshot_location_value', + ) + +def test_save_snapshot_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 = EnvironmentsClient( + 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.save_snapshot 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.save_snapshot] = mock_rpc + request = {} + client.save_snapshot(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.save_snapshot(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_save_snapshot_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 = EnvironmentsAsyncClient( + 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.save_snapshot 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.save_snapshot] = mock_rpc + + request = {} + await client.save_snapshot(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.save_snapshot(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_save_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.SaveSnapshotRequest): + client = EnvironmentsAsyncClient( + 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.save_snapshot), + '__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.save_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.SaveSnapshotRequest() + 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_save_snapshot_async_from_dict(): + await test_save_snapshot_async(request_type=dict) + +def test_save_snapshot_field_headers(): + client = EnvironmentsClient( + 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 = environments.SaveSnapshotRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.save_snapshot(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_save_snapshot_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.SaveSnapshotRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.save_snapshot(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.LoadSnapshotRequest, + dict, +]) +def test_load_snapshot(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.load_snapshot), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.load_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.LoadSnapshotRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_load_snapshot_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 = EnvironmentsClient( + 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 = environments.LoadSnapshotRequest( + environment='environment_value', + snapshot_path='snapshot_path_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.load_snapshot(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.LoadSnapshotRequest( + environment='environment_value', + snapshot_path='snapshot_path_value', + ) + +def test_load_snapshot_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 = EnvironmentsClient( + 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.load_snapshot 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.load_snapshot] = mock_rpc + request = {} + client.load_snapshot(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.load_snapshot(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_load_snapshot_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 = EnvironmentsAsyncClient( + 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.load_snapshot 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.load_snapshot] = mock_rpc + + request = {} + await client.load_snapshot(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.load_snapshot(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_load_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.LoadSnapshotRequest): + client = EnvironmentsAsyncClient( + 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.load_snapshot), + '__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.load_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.LoadSnapshotRequest() + 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_load_snapshot_async_from_dict(): + await test_load_snapshot_async(request_type=dict) + +def test_load_snapshot_field_headers(): + client = EnvironmentsClient( + 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 = environments.LoadSnapshotRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.load_snapshot(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_load_snapshot_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.LoadSnapshotRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.load_snapshot(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.DatabaseFailoverRequest, + dict, +]) +def test_database_failover(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.database_failover), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.database_failover(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.DatabaseFailoverRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_database_failover_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 = EnvironmentsClient( + 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 = environments.DatabaseFailoverRequest( + environment='environment_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.database_failover(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DatabaseFailoverRequest( + environment='environment_value', + ) + +def test_database_failover_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 = EnvironmentsClient( + 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.database_failover 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.database_failover] = mock_rpc + request = {} + client.database_failover(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.database_failover(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_database_failover_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 = EnvironmentsAsyncClient( + 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.database_failover 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.database_failover] = mock_rpc + + request = {} + await client.database_failover(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.database_failover(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_database_failover_async(transport: str = 'grpc_asyncio', request_type=environments.DatabaseFailoverRequest): + client = EnvironmentsAsyncClient( + 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.database_failover), + '__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.database_failover(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.DatabaseFailoverRequest() + 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_database_failover_async_from_dict(): + await test_database_failover_async(request_type=dict) + +def test_database_failover_field_headers(): + client = EnvironmentsClient( + 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 = environments.DatabaseFailoverRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.database_failover(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_database_failover_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.DatabaseFailoverRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.database_failover(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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + environments.FetchDatabasePropertiesRequest, + dict, +]) +def test_fetch_database_properties(request_type, transport: str = 'grpc'): + client = EnvironmentsClient( + 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.fetch_database_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = environments.FetchDatabasePropertiesResponse( + primary_gce_zone='primary_gce_zone_value', + secondary_gce_zone='secondary_gce_zone_value', + is_failover_replica_available=True, + ) + response = client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = environments.FetchDatabasePropertiesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.FetchDatabasePropertiesResponse) + assert response.primary_gce_zone == 'primary_gce_zone_value' + assert response.secondary_gce_zone == 'secondary_gce_zone_value' + assert response.is_failover_replica_available is True + + +def test_fetch_database_properties_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 = EnvironmentsClient( + 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 = environments.FetchDatabasePropertiesRequest( + environment='environment_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.fetch_database_properties(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.FetchDatabasePropertiesRequest( + environment='environment_value', + ) + +def test_fetch_database_properties_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 = EnvironmentsClient( + 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc + request = {} + client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_database_properties(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_fetch_database_properties_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 = EnvironmentsAsyncClient( + 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc + + request = {} + await client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_database_properties(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_fetch_database_properties_async(transport: str = 'grpc_asyncio', request_type=environments.FetchDatabasePropertiesRequest): + client = EnvironmentsAsyncClient( + 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.fetch_database_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse( + primary_gce_zone='primary_gce_zone_value', + secondary_gce_zone='secondary_gce_zone_value', + is_failover_replica_available=True, + )) + response = await client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = environments.FetchDatabasePropertiesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.FetchDatabasePropertiesResponse) + assert response.primary_gce_zone == 'primary_gce_zone_value' + assert response.secondary_gce_zone == 'secondary_gce_zone_value' + assert response.is_failover_replica_available is True + + +@pytest.mark.asyncio +async def test_fetch_database_properties_async_from_dict(): + await test_fetch_database_properties_async(request_type=dict) + +def test_fetch_database_properties_field_headers(): + client = EnvironmentsClient( + 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 = environments.FetchDatabasePropertiesRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + call.return_value = environments.FetchDatabasePropertiesResponse() + client.fetch_database_properties(request) + + # Establish that the 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', + 'environment=environment_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_fetch_database_properties_field_headers_async(): + client = EnvironmentsAsyncClient( + 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 = environments.FetchDatabasePropertiesRequest() + + request.environment = 'environment_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse()) + await client.fetch_database_properties(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', + 'environment=environment_value', + ) in kw['metadata'] + + +def test_create_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + + request = {} + client.create_environment(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_environment(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_environment_rest_flattened(): + client = EnvironmentsClient( + 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', + environment=environments.Environment(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.create_environment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*}/environments" % client.transport._host, args[1]) + + +def test_create_environment_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_environment( + environments.CreateEnvironmentRequest(), + parent='parent_value', + environment=environments.Environment(name='name_value'), + ) + + +def test_get_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + + request = {} + client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_environment(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_environment_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.Environment() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/environments/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 = environments.Environment.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_environment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*}" % client.transport._host, args[1]) + + +def test_get_environment_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_environment( + environments.GetEnvironmentRequest(), + name='name_value', + ) + + +def test_list_environments_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 = EnvironmentsClient( + 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_environments 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_environments] = mock_rpc + + request = {} + client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_environments(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_environments_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.ListEnvironmentsResponse() + + # 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 = environments.ListEnvironmentsResponse.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_environments(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*}/environments" % client.transport._host, args[1]) + + +def test_list_environments_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_environments( + environments.ListEnvironmentsRequest(), + parent='parent_value', + ) + + +def test_list_environments_rest_pager(transport: str = 'rest'): + client = EnvironmentsClient( + 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 = ( + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + environments.Environment(), + ], + next_page_token='abc', + ), + environments.ListEnvironmentsResponse( + environments=[], + next_page_token='def', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + ], + next_page_token='ghi', + ), + environments.ListEnvironmentsResponse( + environments=[ + environments.Environment(), + environments.Environment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(environments.ListEnvironmentsResponse.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_environments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, environments.Environment) + for i in results) + + pages = list(client.list_environments(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + + request = {} + client.update_environment(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_environment(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_environment_rest_required_fields(request_type=environments.UpdateEnvironmentRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_environment._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_environment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EnvironmentsClient( + 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_environment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_environment_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_environment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +def test_update_environment_rest_flattened(): + client = EnvironmentsClient( + 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/environments/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + environment=environments.Environment(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_environment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*}" % client.transport._host, args[1]) + + +def test_update_environment_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_environment( + environments.UpdateEnvironmentRequest(), + name='name_value', + environment=environments.Environment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_environment_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 = EnvironmentsClient( + 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_environment 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_environment] = mock_rpc + + request = {} + client.delete_environment(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_environment(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_environment_rest_flattened(): + client = EnvironmentsClient( + 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/environments/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_environment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*}" % client.transport._host, args[1]) + + +def test_delete_environment_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_environment( + environments.DeleteEnvironmentRequest(), + name='name_value', + ) + + +def test_restart_web_server_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 = EnvironmentsClient( + 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.restart_web_server 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.restart_web_server] = mock_rpc + + request = {} + client.restart_web_server(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.restart_web_server(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_check_upgrade_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 = EnvironmentsClient( + 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.check_upgrade 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.check_upgrade] = mock_rpc + + request = {} + client.check_upgrade(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.check_upgrade(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_execute_airflow_command_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 = EnvironmentsClient( + 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc + + request = {} + client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.execute_airflow_command(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_stop_airflow_command_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 = EnvironmentsClient( + 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc + + request = {} + client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.stop_airflow_command(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_poll_airflow_command_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 = EnvironmentsClient( + 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc + + request = {} + client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.poll_airflow_command(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_workloads_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 = EnvironmentsClient( + 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_workloads 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_workloads] = mock_rpc + + request = {} + client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_workloads(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_workloads_rest_required_fields(request_type=environments.ListWorkloadsRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_workloads._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_workloads._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.ListWorkloadsResponse() + # 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 = environments.ListWorkloadsResponse.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_workloads(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_workloads_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_workloads._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_workloads_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.ListWorkloadsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListWorkloadsResponse.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_workloads(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/environments/*}/workloads" % client.transport._host, args[1]) + + +def test_list_workloads_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_workloads( + environments.ListWorkloadsRequest(), + parent='parent_value', + ) + + +def test_list_workloads_rest_pager(transport: str = 'rest'): + client = EnvironmentsClient( + 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 = ( + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='abc', + ), + environments.ListWorkloadsResponse( + workloads=[], + next_page_token='def', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + next_page_token='ghi', + ), + environments.ListWorkloadsResponse( + workloads=[ + environments.ListWorkloadsResponse.ComposerWorkload(), + environments.ListWorkloadsResponse.ComposerWorkload(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(environments.ListWorkloadsResponse.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/environments/sample3'} + + pager = client.list_workloads(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, environments.ListWorkloadsResponse.ComposerWorkload) + for i in results) + + pages = list(client.list_workloads(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.CreateUserWorkloadsSecretRequest): + transport_class = transports.EnvironmentsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_secret._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_secret._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.UserWorkloadsSecret() + # 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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_user_workloads_secret_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_user_workloads_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "userWorkloadsSecret", ))) + + +def test_create_user_workloads_secret_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets" % client.transport._host, args[1]) + + +def test_create_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.CreateUserWorkloadsSecretRequest(), + parent='parent_value', + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + + +def test_get_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.GetUserWorkloadsSecretRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_secret._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_user_workloads_secret._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.UserWorkloadsSecret() + # 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 = environments.UserWorkloadsSecret.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_user_workloads_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_user_workloads_secret_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_user_workloads_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_user_workloads_secret_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = environments.UserWorkloadsSecret.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_user_workloads_secret(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) + + +def test_get_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.GetUserWorkloadsSecretRequest(), + name='name_value', + ) + + +def test_list_user_workloads_secrets_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 = EnvironmentsClient( + 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc + + request = {} + client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_user_workloads_secrets(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_user_workloads_secrets_rest_required_fields(request_type=environments.ListUserWorkloadsSecretsRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_secrets._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_user_workloads_secrets._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.ListUserWorkloadsSecretsResponse() + # 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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_user_workloads_secrets_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_user_workloads_secrets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_user_workloads_secrets_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.ListUserWorkloadsSecretsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets" % client.transport._host, args[1]) + + +def test_list_user_workloads_secrets_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_secrets( + environments.ListUserWorkloadsSecretsRequest(), + parent='parent_value', + ) + + +def test_list_user_workloads_secrets_rest_pager(transport: str = 'rest'): + client = EnvironmentsClient( + 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 = ( + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[], + next_page_token='def', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsSecretsResponse( + user_workloads_secrets=[ + environments.UserWorkloadsSecret(), + environments.UserWorkloadsSecret(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(environments.ListUserWorkloadsSecretsResponse.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/environments/sample3'} + + pager = client.list_user_workloads_secrets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, environments.UserWorkloadsSecret) + for i in results) + + pages = list(client.list_user_workloads_secrets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_workloads_secret(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_user_workloads_secret_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + user_workloads_secret=environments.UserWorkloadsSecret(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 = environments.UserWorkloadsSecret.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.update_user_workloads_secret(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) + + +def test_update_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.UpdateUserWorkloadsSecretRequest(), + user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), + ) + + +def test_delete_user_workloads_secret_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 = EnvironmentsClient( + 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc + + request = {} + client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.DeleteUserWorkloadsSecretRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_secret._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_user_workloads_secret._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = '' + + response_value._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_user_workloads_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_user_workloads_secret_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_user_workloads_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_user_workloads_secret_rest_flattened(): + client = EnvironmentsClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = '' + response_value._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_user_workloads_secret(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) + + +def test_delete_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_secret( + environments.DeleteUserWorkloadsSecretRequest(), + name='name_value', + ) + + +def test_create_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.CreateUserWorkloadsConfigMapRequest): + transport_class = transports.EnvironmentsRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_config_map._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_config_map._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.UserWorkloadsConfigMap() + # 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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_user_workloads_config_map_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_user_workloads_config_map._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "userWorkloadsConfigMap", ))) + + +def test_create_user_workloads_config_map_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsConfigMap() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps" % client.transport._host, args[1]) + + +def test_create_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.CreateUserWorkloadsConfigMapRequest(), + parent='parent_value', + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + + +def test_get_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.GetUserWorkloadsConfigMapRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_config_map._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_user_workloads_config_map._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.UserWorkloadsConfigMap() + # 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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_user_workloads_config_map_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_user_workloads_config_map._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_user_workloads_config_map_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsConfigMap() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) + + +def test_get_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.GetUserWorkloadsConfigMapRequest(), + name='name_value', + ) + + +def test_list_user_workloads_config_maps_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 = EnvironmentsClient( + 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc + + request = {} + client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_user_workloads_config_maps(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_user_workloads_config_maps_rest_required_fields(request_type=environments.ListUserWorkloadsConfigMapsRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_config_maps._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_user_workloads_config_maps._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.ListUserWorkloadsConfigMapsResponse() + # 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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_user_workloads_config_maps_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_user_workloads_config_maps._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_user_workloads_config_maps_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.ListUserWorkloadsConfigMapsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps" % client.transport._host, args[1]) + + +def test_list_user_workloads_config_maps_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_config_maps( + environments.ListUserWorkloadsConfigMapsRequest(), + parent='parent_value', + ) + + +def test_list_user_workloads_config_maps_rest_pager(transport: str = 'rest'): + client = EnvironmentsClient( + 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 = ( + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + next_page_token='abc', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[], + next_page_token='def', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + ], + next_page_token='ghi', + ), + environments.ListUserWorkloadsConfigMapsResponse( + user_workloads_config_maps=[ + environments.UserWorkloadsConfigMap(), + environments.UserWorkloadsConfigMap(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(environments.ListUserWorkloadsConfigMapsResponse.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/environments/sample3'} + + pager = client.list_user_workloads_config_maps(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, environments.UserWorkloadsConfigMap) + for i in results) + + pages = list(client.list_user_workloads_config_maps(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user_workloads_config_map(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_user_workloads_config_map_rest_flattened(): + client = EnvironmentsClient( + 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 = environments.UserWorkloadsConfigMap() + + # get arguments that satisfy an http rule for this method + sample_request = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + user_workloads_config_map=environments.UserWorkloadsConfigMap(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 = environments.UserWorkloadsConfigMap.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.update_user_workloads_config_map(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) + + +def test_update_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.UpdateUserWorkloadsConfigMapRequest(), + user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), + ) + + +def test_delete_user_workloads_config_map_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 = EnvironmentsClient( + 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc + + request = {} + client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.DeleteUserWorkloadsConfigMapRequest): + transport_class = transports.EnvironmentsRestTransport + + 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_user_workloads_config_map._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_user_workloads_config_map._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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = '' + + response_value._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_user_workloads_config_map(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_user_workloads_config_map_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_user_workloads_config_map._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_user_workloads_config_map_rest_flattened(): + client = EnvironmentsClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = '' + response_value._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_user_workloads_config_map(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) + + +def test_delete_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): + client = EnvironmentsClient( + 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_user_workloads_config_map( + environments.DeleteUserWorkloadsConfigMapRequest(), + name='name_value', + ) + + +def test_save_snapshot_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 = EnvironmentsClient( + 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.save_snapshot 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.save_snapshot] = mock_rpc + + request = {} + client.save_snapshot(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.save_snapshot(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_load_snapshot_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 = EnvironmentsClient( + 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.load_snapshot 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.load_snapshot] = mock_rpc + + request = {} + client.load_snapshot(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.load_snapshot(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_database_failover_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 = EnvironmentsClient( + 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.database_failover 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.database_failover] = mock_rpc + + request = {} + client.database_failover(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.database_failover(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_fetch_database_properties_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 = EnvironmentsClient( + 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc + + request = {} + client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_database_properties(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_fetch_database_properties_rest_required_fields(request_type=environments.FetchDatabasePropertiesRequest): + transport_class = transports.EnvironmentsRestTransport + + request_init = {} + request_init["environment"] = "" + 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()).fetch_database_properties._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["environment"] = 'environment_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_database_properties._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "environment" in jsonified_request + assert jsonified_request["environment"] == 'environment_value' + + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = environments.FetchDatabasePropertiesResponse() + # 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 = environments.FetchDatabasePropertiesResponse.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.fetch_database_properties(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_fetch_database_properties_rest_unset_required_fields(): + transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.fetch_database_properties._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("environment", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EnvironmentsClient( + 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 = EnvironmentsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EnvironmentsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EnvironmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + transports.EnvironmentsRestTransport, +]) +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 = EnvironmentsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = EnvironmentsClient( + 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_environment_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateEnvironmentRequest() + + 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_environment_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value = environments.Environment() + client.get_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetEnvironmentRequest() + + 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_environments_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value = environments.ListEnvironmentsResponse() + client.list_environments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListEnvironmentsRequest() + + 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_environment_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateEnvironmentRequest() + + 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_environment_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteEnvironmentRequest() + + 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_restart_web_server_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restart_web_server), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.restart_web_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.RestartWebServerRequest() + + 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_check_upgrade_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.check_upgrade(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CheckUpgradeRequest() + + 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_execute_airflow_command_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + call.return_value = environments.ExecuteAirflowCommandResponse() + client.execute_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ExecuteAirflowCommandRequest() + + 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_stop_airflow_command_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + call.return_value = environments.StopAirflowCommandResponse() + client.stop_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.StopAirflowCommandRequest() + + 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_poll_airflow_command_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + call.return_value = environments.PollAirflowCommandResponse() + client.poll_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.PollAirflowCommandRequest() + + 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_workloads_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + call.return_value = environments.ListWorkloadsResponse() + client.list_workloads(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListWorkloadsRequest() + + 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_user_workloads_secret_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.create_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.get_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsSecretRequest() + + 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_user_workloads_secrets_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + call.return_value = environments.ListUserWorkloadsSecretsResponse() + client.list_user_workloads_secrets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsSecretsRequest() + + 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_user_workloads_secret_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + call.return_value = environments.UserWorkloadsSecret() + client.update_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + call.return_value = None + client.delete_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsSecretRequest() + + 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_user_workloads_config_map_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.create_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.get_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_maps_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + call.return_value = environments.ListUserWorkloadsConfigMapsResponse() + client.list_user_workloads_config_maps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsConfigMapsRequest() + + 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_user_workloads_config_map_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + call.return_value = environments.UserWorkloadsConfigMap() + client.update_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + call.return_value = None + client.delete_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsConfigMapRequest() + + 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_save_snapshot_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.save_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.SaveSnapshotRequest() + + 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_load_snapshot_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.load_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.LoadSnapshotRequest() + + 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_database_failover_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.database_failover(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DatabaseFailoverRequest() + + 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_fetch_database_properties_empty_call_grpc(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + call.return_value = environments.FetchDatabasePropertiesResponse() + client.fetch_database_properties(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.FetchDatabasePropertiesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = EnvironmentsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = EnvironmentsAsyncClient( + 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_environment_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__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_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateEnvironmentRequest() + + 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_environment_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment( + name='name_value', + uuid='uuid_value', + state=environments.Environment.State.CREATING, + satisfies_pzs=True, + satisfies_pzi=True, + )) + await client.get_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetEnvironmentRequest() + + 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_environments_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse( + next_page_token='next_page_token_value', + )) + await client.list_environments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListEnvironmentsRequest() + + 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_environment_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__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_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateEnvironmentRequest() + + 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_environment_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__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_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteEnvironmentRequest() + + 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_restart_web_server_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restart_web_server), + '__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.restart_web_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.RestartWebServerRequest() + + 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_check_upgrade_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__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.check_upgrade(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CheckUpgradeRequest() + + 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_execute_airflow_command_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse( + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + error='error_value', + )) + await client.execute_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ExecuteAirflowCommandRequest() + + 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_stop_airflow_command_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse( + is_done=True, + output=['output_value'], + )) + await client.stop_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.StopAirflowCommandRequest() + + 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_poll_airflow_command_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse( + output_end=True, + )) + await client.poll_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.PollAirflowCommandRequest() + + 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_workloads_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse( + next_page_token='next_page_token_value', + )) + await client.list_workloads(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListWorkloadsRequest() + + 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_user_workloads_secret_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + await client.create_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + await client.get_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsSecretRequest() + + 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_user_workloads_secrets_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse( + next_page_token='next_page_token_value', + )) + await client.list_user_workloads_secrets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsSecretsRequest() + + 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_user_workloads_secret_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( + name='name_value', + )) + await client.update_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsSecretRequest() + + 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_user_workloads_config_map_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + await client.create_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + await client.get_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_maps_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse( + next_page_token='next_page_token_value', + )) + await client.list_user_workloads_config_maps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsConfigMapsRequest() + + 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_user_workloads_config_map_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( + name='name_value', + )) + await client.update_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsConfigMapRequest() + + 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_save_snapshot_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__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.save_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.SaveSnapshotRequest() + + 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_load_snapshot_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__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.load_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.LoadSnapshotRequest() + + 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_database_failover_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__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.database_failover(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DatabaseFailoverRequest() + + 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_fetch_database_properties_empty_call_grpc_asyncio(): + client = EnvironmentsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse( + primary_gce_zone='primary_gce_zone_value', + secondary_gce_zone='secondary_gce_zone_value', + is_failover_replica_available=True, + )) + await client.fetch_database_properties(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.FetchDatabasePropertiesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = EnvironmentsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_environment_rest_bad_request(request_type=environments.CreateEnvironmentRequest): + client = EnvironmentsClient( + 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_environment(request) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateEnvironmentRequest, + dict, +]) +def test_create_environment_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["environment"] = {'name': 'name_value', 'config': {'gke_cluster': 'gke_cluster_value', 'dag_gcs_prefix': 'dag_gcs_prefix_value', 'node_count': 1070, 'software_config': {'image_version': 'image_version_value', 'airflow_config_overrides': {}, 'pypi_packages': {}, 'env_variables': {}, 'python_version': 'python_version_value', 'scheduler_count': 1607, 'cloud_data_lineage_integration': {'enabled': True}, 'web_server_plugins_mode': 1}, 'node_config': {'location': 'location_value', 'machine_type': 'machine_type_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'disk_size_gb': 1261, 'oauth_scopes': ['oauth_scopes_value1', 'oauth_scopes_value2'], 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'ip_allocation_policy': {'use_ip_aliases': True, 'cluster_secondary_range_name': 'cluster_secondary_range_name_value', 'services_secondary_range_name': 'services_secondary_range_name_value', 'cluster_ipv4_cidr_block': 'cluster_ipv4_cidr_block_value', 'services_ipv4_cidr_block': 'services_ipv4_cidr_block_value'}, 'max_pods_per_node': 1798, 'enable_ip_masq_agent': True, 'composer_network_attachment': 'composer_network_attachment_value', 'composer_internal_ipv4_cidr_block': 'composer_internal_ipv4_cidr_block_value'}, 'private_environment_config': {'enable_private_environment': True, 'enable_private_builds_only': True, 'private_cluster_config': {'enable_private_endpoint': True, 'master_ipv4_cidr_block': 'master_ipv4_cidr_block_value', 'master_ipv4_reserved_range': 'master_ipv4_reserved_range_value'}, 'web_server_ipv4_cidr_block': 'web_server_ipv4_cidr_block_value', 'cloud_sql_ipv4_cidr_block': 'cloud_sql_ipv4_cidr_block_value', 'web_server_ipv4_reserved_range': 'web_server_ipv4_reserved_range_value', 'cloud_composer_network_ipv4_cidr_block': 'cloud_composer_network_ipv4_cidr_block_value', 'cloud_composer_network_ipv4_reserved_range': 'cloud_composer_network_ipv4_reserved_range_value', 'enable_privately_used_public_ips': True, 'cloud_composer_connection_subnetwork': 'cloud_composer_connection_subnetwork_value', 'networking_config': {'connection_type': 1}}, 'web_server_network_access_control': {'allowed_ip_ranges': [{'value': 'value_value', 'description': 'description_value'}]}, 'database_config': {'machine_type': 'machine_type_value', 'zone': 'zone_value'}, 'web_server_config': {'machine_type': 'machine_type_value'}, 'airflow_uri': 'airflow_uri_value', 'airflow_byoid_uri': 'airflow_byoid_uri_value', 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'maintenance_window': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'recurrence': 'recurrence_value'}, 'workloads_config': {'scheduler': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}, 'web_server': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053}, 'worker': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'min_count': 972, 'max_count': 974}, 'triggerer': {'count': 553, 'cpu': 0.328, 'memory_gb': 0.961}, 'dag_processor': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}}, 'environment_size': 1, 'master_authorized_networks_config': {'enabled': True, 'cidr_blocks': [{'display_name': 'display_name_value', 'cidr_block': 'cidr_block_value'}]}, 'recovery_config': {'scheduled_snapshots_config': {'enabled': True, 'snapshot_location': 'snapshot_location_value', 'snapshot_creation_schedule': 'snapshot_creation_schedule_value', 'time_zone': 'time_zone_value'}}, 'data_retention_config': {'airflow_database_retention_days': 3279, 'task_logs_retention_config': {'storage_mode': 1}, 'airflow_metadata_retention_config': {'retention_mode': 1, 'retention_days': 1512}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': True, 'satisfies_pzi': True, 'storage_config': {'bucket': 'bucket_value'}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = environments.CreateEnvironmentRequest.meta.fields["environment"] + + 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["environment"].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["environment"][field])): + del request_init["environment"][field][i][subfield] + else: + del request_init["environment"][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_environment(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_environment_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_environment") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_environment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_environment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.CreateEnvironmentRequest.pb(environments.CreateEnvironmentRequest()) + 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 = environments.CreateEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_environment_rest_bad_request(request_type=environments.GetEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) + + +@pytest.mark.parametrize("request_type", [ + environments.GetEnvironmentRequest, + dict, +]) +def test_get_environment_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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 = environments.Environment( + name='name_value', + uuid='uuid_value', + state=environments.Environment.State.CREATING, + satisfies_pzs=True, + satisfies_pzi=True, + ) + + # 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 = environments.Environment.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_environment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.Environment) + assert response.name == 'name_value' + assert response.uuid == 'uuid_value' + assert response.state == environments.Environment.State.CREATING + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_environment_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_environment") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_environment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_environment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.GetEnvironmentRequest.pb(environments.GetEnvironmentRequest()) + 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 = environments.Environment.to_json(environments.Environment()) + req.return_value.content = return_value + + request = environments.GetEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.Environment() + post_with_metadata.return_value = environments.Environment(), metadata + + client.get_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_environments_rest_bad_request(request_type=environments.ListEnvironmentsRequest): + client = EnvironmentsClient( + 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_environments(request) + + +@pytest.mark.parametrize("request_type", [ + environments.ListEnvironmentsRequest, + dict, +]) +def test_list_environments_rest_call_success(request_type): + client = EnvironmentsClient( + 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 = environments.ListEnvironmentsResponse( + 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 = environments.ListEnvironmentsResponse.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_environments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnvironmentsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_environments_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_environments") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_environments_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_environments") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.ListEnvironmentsRequest.pb(environments.ListEnvironmentsRequest()) + 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 = environments.ListEnvironmentsResponse.to_json(environments.ListEnvironmentsResponse()) + req.return_value.content = return_value + + request = environments.ListEnvironmentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListEnvironmentsResponse() + post_with_metadata.return_value = environments.ListEnvironmentsResponse(), metadata + + client.list_environments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_environment_rest_bad_request(request_type=environments.UpdateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateEnvironmentRequest, + dict, +]) +def test_update_environment_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3'} + request_init["environment"] = {'name': 'name_value', 'config': {'gke_cluster': 'gke_cluster_value', 'dag_gcs_prefix': 'dag_gcs_prefix_value', 'node_count': 1070, 'software_config': {'image_version': 'image_version_value', 'airflow_config_overrides': {}, 'pypi_packages': {}, 'env_variables': {}, 'python_version': 'python_version_value', 'scheduler_count': 1607, 'cloud_data_lineage_integration': {'enabled': True}, 'web_server_plugins_mode': 1}, 'node_config': {'location': 'location_value', 'machine_type': 'machine_type_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'disk_size_gb': 1261, 'oauth_scopes': ['oauth_scopes_value1', 'oauth_scopes_value2'], 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'ip_allocation_policy': {'use_ip_aliases': True, 'cluster_secondary_range_name': 'cluster_secondary_range_name_value', 'services_secondary_range_name': 'services_secondary_range_name_value', 'cluster_ipv4_cidr_block': 'cluster_ipv4_cidr_block_value', 'services_ipv4_cidr_block': 'services_ipv4_cidr_block_value'}, 'max_pods_per_node': 1798, 'enable_ip_masq_agent': True, 'composer_network_attachment': 'composer_network_attachment_value', 'composer_internal_ipv4_cidr_block': 'composer_internal_ipv4_cidr_block_value'}, 'private_environment_config': {'enable_private_environment': True, 'enable_private_builds_only': True, 'private_cluster_config': {'enable_private_endpoint': True, 'master_ipv4_cidr_block': 'master_ipv4_cidr_block_value', 'master_ipv4_reserved_range': 'master_ipv4_reserved_range_value'}, 'web_server_ipv4_cidr_block': 'web_server_ipv4_cidr_block_value', 'cloud_sql_ipv4_cidr_block': 'cloud_sql_ipv4_cidr_block_value', 'web_server_ipv4_reserved_range': 'web_server_ipv4_reserved_range_value', 'cloud_composer_network_ipv4_cidr_block': 'cloud_composer_network_ipv4_cidr_block_value', 'cloud_composer_network_ipv4_reserved_range': 'cloud_composer_network_ipv4_reserved_range_value', 'enable_privately_used_public_ips': True, 'cloud_composer_connection_subnetwork': 'cloud_composer_connection_subnetwork_value', 'networking_config': {'connection_type': 1}}, 'web_server_network_access_control': {'allowed_ip_ranges': [{'value': 'value_value', 'description': 'description_value'}]}, 'database_config': {'machine_type': 'machine_type_value', 'zone': 'zone_value'}, 'web_server_config': {'machine_type': 'machine_type_value'}, 'airflow_uri': 'airflow_uri_value', 'airflow_byoid_uri': 'airflow_byoid_uri_value', 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'maintenance_window': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'recurrence': 'recurrence_value'}, 'workloads_config': {'scheduler': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}, 'web_server': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053}, 'worker': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'min_count': 972, 'max_count': 974}, 'triggerer': {'count': 553, 'cpu': 0.328, 'memory_gb': 0.961}, 'dag_processor': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}}, 'environment_size': 1, 'master_authorized_networks_config': {'enabled': True, 'cidr_blocks': [{'display_name': 'display_name_value', 'cidr_block': 'cidr_block_value'}]}, 'recovery_config': {'scheduled_snapshots_config': {'enabled': True, 'snapshot_location': 'snapshot_location_value', 'snapshot_creation_schedule': 'snapshot_creation_schedule_value', 'time_zone': 'time_zone_value'}}, 'data_retention_config': {'airflow_database_retention_days': 3279, 'task_logs_retention_config': {'storage_mode': 1}, 'airflow_metadata_retention_config': {'retention_mode': 1, 'retention_days': 1512}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': True, 'satisfies_pzi': True, 'storage_config': {'bucket': 'bucket_value'}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = environments.UpdateEnvironmentRequest.meta.fields["environment"] + + 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["environment"].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["environment"][field])): + del request_init["environment"][field][i][subfield] + else: + del request_init["environment"][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_environment(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_environment_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_environment") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_environment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_environment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.UpdateEnvironmentRequest.pb(environments.UpdateEnvironmentRequest()) + 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 = environments.UpdateEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_environment_rest_bad_request(request_type=environments.DeleteEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteEnvironmentRequest, + dict, +]) +def test_delete_environment_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(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_environment_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_delete_environment") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_delete_environment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_delete_environment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.DeleteEnvironmentRequest.pb(environments.DeleteEnvironmentRequest()) + 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 = environments.DeleteEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_restart_web_server_rest_bad_request(request_type=environments.RestartWebServerRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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.restart_web_server(request) + + +@pytest.mark.parametrize("request_type", [ + environments.RestartWebServerRequest, + dict, +]) +def test_restart_web_server_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/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.restart_web_server(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_restart_web_server_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_restart_web_server") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_restart_web_server_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_restart_web_server") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.RestartWebServerRequest.pb(environments.RestartWebServerRequest()) + 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 = environments.RestartWebServerRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.restart_web_server(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_check_upgrade_rest_bad_request(request_type=environments.CheckUpgradeRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.check_upgrade(request) + + +@pytest.mark.parametrize("request_type", [ + environments.CheckUpgradeRequest, + dict, +]) +def test_check_upgrade_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.check_upgrade(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_check_upgrade_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_check_upgrade") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_check_upgrade_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_check_upgrade") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.CheckUpgradeRequest.pb(environments.CheckUpgradeRequest()) + 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 = environments.CheckUpgradeRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.check_upgrade(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_execute_airflow_command_rest_bad_request(request_type=environments.ExecuteAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.execute_airflow_command(request) + + +@pytest.mark.parametrize("request_type", [ + environments.ExecuteAirflowCommandRequest, + dict, +]) +def test_execute_airflow_command_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.ExecuteAirflowCommandResponse( + execution_id='execution_id_value', + pod='pod_value', + pod_namespace='pod_namespace_value', + error='error_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 = environments.ExecuteAirflowCommandResponse.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.execute_airflow_command(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.ExecuteAirflowCommandResponse) + assert response.execution_id == 'execution_id_value' + assert response.pod == 'pod_value' + assert response.pod_namespace == 'pod_namespace_value' + assert response.error == 'error_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_execute_airflow_command_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_execute_airflow_command") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_execute_airflow_command_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_execute_airflow_command") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.ExecuteAirflowCommandRequest.pb(environments.ExecuteAirflowCommandRequest()) + 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 = environments.ExecuteAirflowCommandResponse.to_json(environments.ExecuteAirflowCommandResponse()) + req.return_value.content = return_value + + request = environments.ExecuteAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ExecuteAirflowCommandResponse() + post_with_metadata.return_value = environments.ExecuteAirflowCommandResponse(), metadata + + client.execute_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_stop_airflow_command_rest_bad_request(request_type=environments.StopAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.stop_airflow_command(request) + + +@pytest.mark.parametrize("request_type", [ + environments.StopAirflowCommandRequest, + dict, +]) +def test_stop_airflow_command_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.StopAirflowCommandResponse( + is_done=True, + output=['output_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 = environments.StopAirflowCommandResponse.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.stop_airflow_command(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ['output_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_airflow_command_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_stop_airflow_command") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_stop_airflow_command_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_stop_airflow_command") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.StopAirflowCommandRequest.pb(environments.StopAirflowCommandRequest()) + 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 = environments.StopAirflowCommandResponse.to_json(environments.StopAirflowCommandResponse()) + req.return_value.content = return_value + + request = environments.StopAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.StopAirflowCommandResponse() + post_with_metadata.return_value = environments.StopAirflowCommandResponse(), metadata + + client.stop_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_poll_airflow_command_rest_bad_request(request_type=environments.PollAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.poll_airflow_command(request) + + +@pytest.mark.parametrize("request_type", [ + environments.PollAirflowCommandRequest, + dict, +]) +def test_poll_airflow_command_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.PollAirflowCommandResponse( + output_end=True, + ) + + # 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 = environments.PollAirflowCommandResponse.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.poll_airflow_command(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.PollAirflowCommandResponse) + assert response.output_end is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_poll_airflow_command_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_poll_airflow_command") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_poll_airflow_command_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_poll_airflow_command") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.PollAirflowCommandRequest.pb(environments.PollAirflowCommandRequest()) + 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 = environments.PollAirflowCommandResponse.to_json(environments.PollAirflowCommandResponse()) + req.return_value.content = return_value + + request = environments.PollAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.PollAirflowCommandResponse() + post_with_metadata.return_value = environments.PollAirflowCommandResponse(), metadata + + client.poll_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_workloads_rest_bad_request(request_type=environments.ListWorkloadsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_workloads(request) + + +@pytest.mark.parametrize("request_type", [ + environments.ListWorkloadsRequest, + dict, +]) +def test_list_workloads_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListWorkloadsResponse( + 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 = environments.ListWorkloadsResponse.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_workloads(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workloads_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_workloads") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_workloads_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_workloads") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.ListWorkloadsRequest.pb(environments.ListWorkloadsRequest()) + 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 = environments.ListWorkloadsResponse.to_json(environments.ListWorkloadsResponse()) + req.return_value.content = return_value + + request = environments.ListWorkloadsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListWorkloadsResponse() + post_with_metadata.return_value = environments.ListWorkloadsResponse(), metadata + + client.list_workloads(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_user_workloads_secret_rest_bad_request(request_type=environments.CreateUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_secret(request) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsSecretRequest, + dict, +]) +def test_create_user_workloads_secret_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} + request_init["user_workloads_secret"] = {'name': 'name_value', 'data': {}} + # 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 = environments.CreateUserWorkloadsSecretRequest.meta.fields["user_workloads_secret"] + + 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["user_workloads_secret"].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["user_workloads_secret"][field])): + del request_init["user_workloads_secret"][field][i][subfield] + else: + del request_init["user_workloads_secret"][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 = environments.UserWorkloadsSecret( + 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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_workloads_secret_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_user_workloads_secret") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_user_workloads_secret_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_user_workloads_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.CreateUserWorkloadsSecretRequest.pb(environments.CreateUserWorkloadsSecretRequest()) + 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + req.return_value.content = return_value + + request = environments.CreateUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata + + client.create_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_user_workloads_secret_rest_bad_request(request_type=environments.GetUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsSecretRequest, + dict, +]) +def test_get_user_workloads_secret_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = environments.UserWorkloadsSecret( + 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 = environments.UserWorkloadsSecret.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_user_workloads_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_workloads_secret_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_user_workloads_secret") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_user_workloads_secret_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_user_workloads_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.GetUserWorkloadsSecretRequest.pb(environments.GetUserWorkloadsSecretRequest()) + 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + req.return_value.content = return_value + + request = environments.GetUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata + + client.get_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_user_workloads_secrets_rest_bad_request(request_type=environments.ListUserWorkloadsSecretsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_secrets(request) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsSecretsRequest, + dict, +]) +def test_list_user_workloads_secrets_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsSecretsResponse( + 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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsSecretsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_user_workloads_secrets_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_user_workloads_secrets") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_user_workloads_secrets_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_user_workloads_secrets") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.ListUserWorkloadsSecretsRequest.pb(environments.ListUserWorkloadsSecretsRequest()) + 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 = environments.ListUserWorkloadsSecretsResponse.to_json(environments.ListUserWorkloadsSecretsResponse()) + req.return_value.content = return_value + + request = environments.ListUserWorkloadsSecretsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListUserWorkloadsSecretsResponse() + post_with_metadata.return_value = environments.ListUserWorkloadsSecretsResponse(), metadata + + client.list_user_workloads_secrets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_user_workloads_secret_rest_bad_request(request_type=environments.UpdateUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateUserWorkloadsSecretRequest, + dict, +]) +def test_update_user_workloads_secret_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4'}} + request_init["user_workloads_secret"] = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4', 'data': {}} + # 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 = environments.UpdateUserWorkloadsSecretRequest.meta.fields["user_workloads_secret"] + + 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["user_workloads_secret"].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["user_workloads_secret"][field])): + del request_init["user_workloads_secret"][field][i][subfield] + else: + del request_init["user_workloads_secret"][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 = environments.UserWorkloadsSecret( + 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 = environments.UserWorkloadsSecret.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.update_user_workloads_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsSecret) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_workloads_secret_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_user_workloads_secret") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_user_workloads_secret_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_user_workloads_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.UpdateUserWorkloadsSecretRequest.pb(environments.UpdateUserWorkloadsSecretRequest()) + 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + req.return_value.content = return_value + + request = environments.UpdateUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata + + client.update_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_user_workloads_secret_rest_bad_request(request_type=environments.DeleteUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsSecretRequest, + dict, +]) +def test_delete_user_workloads_secret_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = 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_user_workloads_secret(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_user_workloads_secret_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "pre_delete_user_workloads_secret") as pre: + pre.assert_not_called() + pb_message = environments.DeleteUserWorkloadsSecretRequest.pb(environments.DeleteUserWorkloadsSecretRequest()) + 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"} + + request = environments.DeleteUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_create_user_workloads_config_map_rest_bad_request(request_type=environments.CreateUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_config_map(request) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsConfigMapRequest, + dict, +]) +def test_create_user_workloads_config_map_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} + request_init["user_workloads_config_map"] = {'name': 'name_value', 'data': {}} + # 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 = environments.CreateUserWorkloadsConfigMapRequest.meta.fields["user_workloads_config_map"] + + 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["user_workloads_config_map"].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["user_workloads_config_map"][field])): + del request_init["user_workloads_config_map"][field][i][subfield] + else: + del request_init["user_workloads_config_map"][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 = environments.UserWorkloadsConfigMap( + 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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_workloads_config_map_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_user_workloads_config_map") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_user_workloads_config_map_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_user_workloads_config_map") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.CreateUserWorkloadsConfigMapRequest.pb(environments.CreateUserWorkloadsConfigMapRequest()) + 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + req.return_value.content = return_value + + request = environments.CreateUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata + + client.create_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_user_workloads_config_map_rest_bad_request(request_type=environments.GetUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsConfigMapRequest, + dict, +]) +def test_get_user_workloads_config_map_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = environments.UserWorkloadsConfigMap( + 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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_workloads_config_map_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_user_workloads_config_map") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_user_workloads_config_map_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_user_workloads_config_map") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.GetUserWorkloadsConfigMapRequest.pb(environments.GetUserWorkloadsConfigMapRequest()) + 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + req.return_value.content = return_value + + request = environments.GetUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata + + client.get_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_user_workloads_config_maps_rest_bad_request(request_type=environments.ListUserWorkloadsConfigMapsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_config_maps(request) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsConfigMapsRequest, + dict, +]) +def test_list_user_workloads_config_maps_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsConfigMapsResponse( + 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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserWorkloadsConfigMapsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_user_workloads_config_maps_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_user_workloads_config_maps") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_user_workloads_config_maps_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_user_workloads_config_maps") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.ListUserWorkloadsConfigMapsRequest.pb(environments.ListUserWorkloadsConfigMapsRequest()) + 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 = environments.ListUserWorkloadsConfigMapsResponse.to_json(environments.ListUserWorkloadsConfigMapsResponse()) + req.return_value.content = return_value + + request = environments.ListUserWorkloadsConfigMapsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListUserWorkloadsConfigMapsResponse() + post_with_metadata.return_value = environments.ListUserWorkloadsConfigMapsResponse(), metadata + + client.list_user_workloads_config_maps(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_user_workloads_config_map_rest_bad_request(request_type=environments.UpdateUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateUserWorkloadsConfigMapRequest, + dict, +]) +def test_update_user_workloads_config_map_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4'}} + request_init["user_workloads_config_map"] = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4', 'data': {}} + # 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 = environments.UpdateUserWorkloadsConfigMapRequest.meta.fields["user_workloads_config_map"] + + 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["user_workloads_config_map"].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["user_workloads_config_map"][field])): + del request_init["user_workloads_config_map"][field][i][subfield] + else: + del request_init["user_workloads_config_map"][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 = environments.UserWorkloadsConfigMap( + 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 = environments.UserWorkloadsConfigMap.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.update_user_workloads_config_map(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.UserWorkloadsConfigMap) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_workloads_config_map_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_user_workloads_config_map") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_user_workloads_config_map_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_user_workloads_config_map") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.UpdateUserWorkloadsConfigMapRequest.pb(environments.UpdateUserWorkloadsConfigMapRequest()) + 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + req.return_value.content = return_value + + request = environments.UpdateUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata + + client.update_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_user_workloads_config_map_rest_bad_request(request_type=environments.DeleteUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsConfigMapRequest, + dict, +]) +def test_delete_user_workloads_config_map_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = 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_user_workloads_config_map(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_user_workloads_config_map_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "pre_delete_user_workloads_config_map") as pre: + pre.assert_not_called() + pb_message = environments.DeleteUserWorkloadsConfigMapRequest.pb(environments.DeleteUserWorkloadsConfigMapRequest()) + 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"} + + request = environments.DeleteUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_save_snapshot_rest_bad_request(request_type=environments.SaveSnapshotRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.save_snapshot(request) + + +@pytest.mark.parametrize("request_type", [ + environments.SaveSnapshotRequest, + dict, +]) +def test_save_snapshot_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.save_snapshot(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_save_snapshot_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_save_snapshot") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_save_snapshot_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_save_snapshot") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.SaveSnapshotRequest.pb(environments.SaveSnapshotRequest()) + 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 = environments.SaveSnapshotRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.save_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_load_snapshot_rest_bad_request(request_type=environments.LoadSnapshotRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.load_snapshot(request) + + +@pytest.mark.parametrize("request_type", [ + environments.LoadSnapshotRequest, + dict, +]) +def test_load_snapshot_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.load_snapshot(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_load_snapshot_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_load_snapshot") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_load_snapshot_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_load_snapshot") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.LoadSnapshotRequest.pb(environments.LoadSnapshotRequest()) + 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 = environments.LoadSnapshotRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.load_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_database_failover_rest_bad_request(request_type=environments.DatabaseFailoverRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.database_failover(request) + + +@pytest.mark.parametrize("request_type", [ + environments.DatabaseFailoverRequest, + dict, +]) +def test_database_failover_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.database_failover(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_database_failover_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_database_failover") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_database_failover_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_database_failover") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.DatabaseFailoverRequest.pb(environments.DatabaseFailoverRequest()) + 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 = environments.DatabaseFailoverRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.database_failover(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_fetch_database_properties_rest_bad_request(request_type=environments.FetchDatabasePropertiesRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.fetch_database_properties(request) + + +@pytest.mark.parametrize("request_type", [ + environments.FetchDatabasePropertiesRequest, + dict, +]) +def test_fetch_database_properties_rest_call_success(request_type): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.FetchDatabasePropertiesResponse( + primary_gce_zone='primary_gce_zone_value', + secondary_gce_zone='secondary_gce_zone_value', + is_failover_replica_available=True, + ) + + # 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 = environments.FetchDatabasePropertiesResponse.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.fetch_database_properties(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, environments.FetchDatabasePropertiesResponse) + assert response.primary_gce_zone == 'primary_gce_zone_value' + assert response.secondary_gce_zone == 'secondary_gce_zone_value' + assert response.is_failover_replica_available is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_database_properties_rest_interceptors(null_interceptor): + transport = transports.EnvironmentsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), + ) + client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_fetch_database_properties") as post, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "post_fetch_database_properties_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_fetch_database_properties") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = environments.FetchDatabasePropertiesRequest.pb(environments.FetchDatabasePropertiesRequest()) + 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 = environments.FetchDatabasePropertiesResponse.to_json(environments.FetchDatabasePropertiesResponse()) + req.return_value.content = return_value + + request = environments.FetchDatabasePropertiesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.FetchDatabasePropertiesResponse() + post_with_metadata.return_value = environments.FetchDatabasePropertiesResponse(), metadata + + client.fetch_database_properties(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = EnvironmentsClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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_environment_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + client.create_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateEnvironmentRequest() + + 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_environment_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + client.get_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetEnvironmentRequest() + + 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_environments_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + client.list_environments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListEnvironmentsRequest() + + 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_environment_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + client.update_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateEnvironmentRequest() + + 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_environment_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + client.delete_environment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteEnvironmentRequest() + + 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_restart_web_server_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restart_web_server), + '__call__') as call: + client.restart_web_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.RestartWebServerRequest() + + 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_check_upgrade_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + client.check_upgrade(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CheckUpgradeRequest() + + 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_execute_airflow_command_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.execute_airflow_command), + '__call__') as call: + client.execute_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ExecuteAirflowCommandRequest() + + 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_stop_airflow_command_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.stop_airflow_command), + '__call__') as call: + client.stop_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.StopAirflowCommandRequest() + + 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_poll_airflow_command_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.poll_airflow_command), + '__call__') as call: + client.poll_airflow_command(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.PollAirflowCommandRequest() + + 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_workloads_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + client.list_workloads(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListWorkloadsRequest() + + 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_user_workloads_secret_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_secret), + '__call__') as call: + client.create_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_secret), + '__call__') as call: + client.get_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsSecretRequest() + + 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_user_workloads_secrets_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_secrets), + '__call__') as call: + client.list_user_workloads_secrets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsSecretsRequest() + + 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_user_workloads_secret_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_secret), + '__call__') as call: + client.update_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsSecretRequest() + + 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_user_workloads_secret_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_secret), + '__call__') as call: + client.delete_user_workloads_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsSecretRequest() + + 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_user_workloads_config_map_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user_workloads_config_map), + '__call__') as call: + client.create_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.CreateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user_workloads_config_map), + '__call__') as call: + client.get_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.GetUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_maps_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_user_workloads_config_maps), + '__call__') as call: + client.list_user_workloads_config_maps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.ListUserWorkloadsConfigMapsRequest() + + 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_user_workloads_config_map_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user_workloads_config_map), + '__call__') as call: + client.update_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.UpdateUserWorkloadsConfigMapRequest() + + 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_user_workloads_config_map_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user_workloads_config_map), + '__call__') as call: + client.delete_user_workloads_config_map(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DeleteUserWorkloadsConfigMapRequest() + + 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_save_snapshot_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + client.save_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.SaveSnapshotRequest() + + 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_load_snapshot_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + client.load_snapshot(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.LoadSnapshotRequest() + + 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_database_failover_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + client.database_failover(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.DatabaseFailoverRequest() + + 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_fetch_database_properties_empty_call_rest(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_database_properties), + '__call__') as call: + client.fetch_database_properties(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = environments.FetchDatabasePropertiesRequest() + + assert args[0] == request_msg + + +def test_environments_rest_lro_client(): + client = EnvironmentsClient( + 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 = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EnvironmentsGrpcTransport, + ) + +def test_environments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_environments_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.orchestration.airflow.service_v1beta1.services.environments.transports.EnvironmentsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_environment', + 'get_environment', + 'list_environments', + 'update_environment', + 'delete_environment', + 'restart_web_server', + 'check_upgrade', + 'execute_airflow_command', + 'stop_airflow_command', + 'poll_airflow_command', + 'list_workloads', + 'create_user_workloads_secret', + 'get_user_workloads_secret', + 'list_user_workloads_secrets', + 'update_user_workloads_secret', + 'delete_user_workloads_secret', + 'create_user_workloads_config_map', + 'get_user_workloads_config_map', + 'list_user_workloads_config_maps', + 'update_user_workloads_config_map', + 'delete_user_workloads_config_map', + 'save_snapshot', + 'load_snapshot', + 'database_failover', + 'fetch_database_properties', + 'get_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_environments_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.orchestration.airflow.service_v1beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + 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_environments_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.orchestration.airflow.service_v1beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport() + adc.assert_called_once() + + +def test_environments_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) + EnvironmentsClient() + 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.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +def test_environments_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.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + transports.EnvironmentsRestTransport, + ], +) +def test_environments_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.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_environments_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( + "composer.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="composer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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_environments_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.EnvironmentsRestTransport ( + 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_environments_host_no_port(transport_name): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://composer.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_environments_host_with_port(transport_name): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'composer.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://composer.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_environments_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EnvironmentsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EnvironmentsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_environment._session + session2 = client2.transport.create_environment._session + assert session1 != session2 + session1 = client1.transport.get_environment._session + session2 = client2.transport.get_environment._session + assert session1 != session2 + session1 = client1.transport.list_environments._session + session2 = client2.transport.list_environments._session + assert session1 != session2 + session1 = client1.transport.update_environment._session + session2 = client2.transport.update_environment._session + assert session1 != session2 + session1 = client1.transport.delete_environment._session + session2 = client2.transport.delete_environment._session + assert session1 != session2 + session1 = client1.transport.restart_web_server._session + session2 = client2.transport.restart_web_server._session + assert session1 != session2 + session1 = client1.transport.check_upgrade._session + session2 = client2.transport.check_upgrade._session + assert session1 != session2 + session1 = client1.transport.execute_airflow_command._session + session2 = client2.transport.execute_airflow_command._session + assert session1 != session2 + session1 = client1.transport.stop_airflow_command._session + session2 = client2.transport.stop_airflow_command._session + assert session1 != session2 + session1 = client1.transport.poll_airflow_command._session + session2 = client2.transport.poll_airflow_command._session + assert session1 != session2 + session1 = client1.transport.list_workloads._session + session2 = client2.transport.list_workloads._session + assert session1 != session2 + session1 = client1.transport.create_user_workloads_secret._session + session2 = client2.transport.create_user_workloads_secret._session + assert session1 != session2 + session1 = client1.transport.get_user_workloads_secret._session + session2 = client2.transport.get_user_workloads_secret._session + assert session1 != session2 + session1 = client1.transport.list_user_workloads_secrets._session + session2 = client2.transport.list_user_workloads_secrets._session + assert session1 != session2 + session1 = client1.transport.update_user_workloads_secret._session + session2 = client2.transport.update_user_workloads_secret._session + assert session1 != session2 + session1 = client1.transport.delete_user_workloads_secret._session + session2 = client2.transport.delete_user_workloads_secret._session + assert session1 != session2 + session1 = client1.transport.create_user_workloads_config_map._session + session2 = client2.transport.create_user_workloads_config_map._session + assert session1 != session2 + session1 = client1.transport.get_user_workloads_config_map._session + session2 = client2.transport.get_user_workloads_config_map._session + assert session1 != session2 + session1 = client1.transport.list_user_workloads_config_maps._session + session2 = client2.transport.list_user_workloads_config_maps._session + assert session1 != session2 + session1 = client1.transport.update_user_workloads_config_map._session + session2 = client2.transport.update_user_workloads_config_map._session + assert session1 != session2 + session1 = client1.transport.delete_user_workloads_config_map._session + session2 = client2.transport.delete_user_workloads_config_map._session + assert session1 != session2 + session1 = client1.transport.save_snapshot._session + session2 = client2.transport.save_snapshot._session + assert session1 != session2 + session1 = client1.transport.load_snapshot._session + session2 = client2.transport.load_snapshot._session + assert session1 != session2 + session1 = client1.transport.database_failover._session + session2 = client2.transport.database_failover._session + assert session1 != session2 + session1 = client1.transport.fetch_database_properties._session + session2 = client2.transport.fetch_database_properties._session + assert session1 != session2 +def test_environments_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EnvironmentsGrpcTransport( + 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_environments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EnvironmentsGrpcAsyncIOTransport( + 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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) +def test_environments_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_environments_grpc_lro_client(): + client = EnvironmentsClient( + 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_environments_grpc_lro_async_client(): + client = EnvironmentsAsyncClient( + 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_environment_path(): + project = "squid" + location = "clam" + environment = "whelk" + expected = "projects/{project}/locations/{location}/environments/{environment}".format(project=project, location=location, environment=environment, ) + actual = EnvironmentsClient.environment_path(project, location, environment) + assert expected == actual + + +def test_parse_environment_path(): + expected = { + "project": "octopus", + "location": "oyster", + "environment": "nudibranch", + } + path = EnvironmentsClient.environment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_environment_path(path) + assert expected == actual + +def test_user_workloads_config_map_path(): + project = "cuttlefish" + location = "mussel" + environment = "winkle" + user_workloads_config_map = "nautilus" + expected = "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsConfigMaps/{user_workloads_config_map}".format(project=project, location=location, environment=environment, user_workloads_config_map=user_workloads_config_map, ) + actual = EnvironmentsClient.user_workloads_config_map_path(project, location, environment, user_workloads_config_map) + assert expected == actual + + +def test_parse_user_workloads_config_map_path(): + expected = { + "project": "scallop", + "location": "abalone", + "environment": "squid", + "user_workloads_config_map": "clam", + } + path = EnvironmentsClient.user_workloads_config_map_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_user_workloads_config_map_path(path) + assert expected == actual + +def test_user_workloads_secret_path(): + project = "whelk" + location = "octopus" + environment = "oyster" + user_workloads_secret = "nudibranch" + expected = "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsSecrets/{user_workloads_secret}".format(project=project, location=location, environment=environment, user_workloads_secret=user_workloads_secret, ) + actual = EnvironmentsClient.user_workloads_secret_path(project, location, environment, user_workloads_secret) + assert expected == actual + + +def test_parse_user_workloads_secret_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "environment": "winkle", + "user_workloads_secret": "nautilus", + } + path = EnvironmentsClient.user_workloads_secret_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_user_workloads_secret_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EnvironmentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = EnvironmentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = EnvironmentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = EnvironmentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = EnvironmentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.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 = EnvironmentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = EnvironmentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.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.EnvironmentsTransport, '_prep_wrapped_messages') as prep: + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EnvironmentsTransport, '_prep_wrapped_messages') as prep: + transport_class = EnvironmentsClient.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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsAsyncClient( + 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 = EnvironmentsClient( + 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 = EnvironmentsClient( + 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", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport), + (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport), +]) +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-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py new file mode 100644 index 000000000000..11fbd69f4024 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py @@ -0,0 +1,2847 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +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.orchestration.airflow.service_v1beta1.services.image_versions import ImageVersionsAsyncClient +from google.cloud.orchestration.airflow.service_v1beta1.services.image_versions import ImageVersionsClient +from google.cloud.orchestration.airflow.service_v1beta1.services.image_versions import pagers +from google.cloud.orchestration.airflow.service_v1beta1.services.image_versions import transports +from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +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 ImageVersionsClient._get_default_mtls_endpoint(None) is None + assert ImageVersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ImageVersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ImageVersionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ImageVersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ImageVersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ImageVersionsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ImageVersionsClient._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 ImageVersionsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ImageVersionsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ImageVersionsClient._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 ImageVersionsClient._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 ImageVersionsClient._get_client_cert_source(None, False) is None + assert ImageVersionsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ImageVersionsClient._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 ImageVersionsClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ImageVersionsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ImageVersionsClient._DEFAULT_UNIVERSE + default_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ImageVersionsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ImageVersionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "always") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + assert ImageVersionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + assert ImageVersionsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ImageVersionsClient._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 ImageVersionsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ImageVersionsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ImageVersionsClient._get_universe_domain(None, None) == ImageVersionsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ImageVersionsClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = ImageVersionsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = ImageVersionsClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (ImageVersionsClient, "grpc"), + (ImageVersionsAsyncClient, "grpc_asyncio"), + (ImageVersionsClient, "rest"), +]) +def test_image_versions_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 == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://composer.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ImageVersionsGrpcTransport, "grpc"), + (transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ImageVersionsRestTransport, "rest"), +]) +def test_image_versions_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", [ + (ImageVersionsClient, "grpc"), + (ImageVersionsAsyncClient, "grpc_asyncio"), + (ImageVersionsClient, "rest"), +]) +def test_image_versions_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 == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://composer.googleapis.com' + ) + + +def test_image_versions_client_get_transport_class(): + transport = ImageVersionsClient.get_transport_class() + available_transports = [ + transports.ImageVersionsGrpcTransport, + transports.ImageVersionsRestTransport, + ] + assert transport in available_transports + + transport = ImageVersionsClient.get_transport_class("grpc") + assert transport == transports.ImageVersionsGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), +]) +@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) +def test_image_versions_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(ImageVersionsClient, '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(ImageVersionsClient, '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", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", "true"), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", "false"), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", "true"), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", "false"), +]) +@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_image_versions_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", [ + ImageVersionsClient, ImageVersionsAsyncClient +]) +@mock.patch.object(ImageVersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageVersionsAsyncClient)) +def test_image_versions_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", [ + ImageVersionsClient, ImageVersionsAsyncClient +]) +@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) +def test_image_versions_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ImageVersionsClient._DEFAULT_UNIVERSE + default_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ImageVersionsClient._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", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), +]) +def test_image_versions_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", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", grpc_helpers), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", None), +]) +def test_image_versions_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_image_versions_client_client_options_from_dict(): + with mock.patch('google.cloud.orchestration.airflow.service_v1beta1.services.image_versions.transports.ImageVersionsGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ImageVersionsClient( + 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", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", grpc_helpers), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_image_versions_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( + "composer.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="composer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + image_versions.ListImageVersionsRequest, + dict, +]) +def test_list_image_versions(request_type, transport: str = 'grpc'): + client = ImageVersionsClient( + 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_image_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = image_versions.ListImageVersionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = image_versions.ListImageVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImageVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_image_versions_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 = ImageVersionsClient( + 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 = image_versions.ListImageVersionsRequest( + 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_image_versions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_image_versions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == image_versions.ListImageVersionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_image_versions_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 = ImageVersionsClient( + 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_image_versions 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_image_versions] = mock_rpc + request = {} + client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_image_versions(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_image_versions_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 = ImageVersionsAsyncClient( + 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_image_versions 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_image_versions] = mock_rpc + + request = {} + await client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_image_versions(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_image_versions_async(transport: str = 'grpc_asyncio', request_type=image_versions.ListImageVersionsRequest): + client = ImageVersionsAsyncClient( + 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_image_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = image_versions.ListImageVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImageVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_image_versions_async_from_dict(): + await test_list_image_versions_async(request_type=dict) + +def test_list_image_versions_field_headers(): + client = ImageVersionsClient( + 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 = image_versions.ListImageVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + call.return_value = image_versions.ListImageVersionsResponse() + client.list_image_versions(request) + + # Establish that the 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_image_versions_field_headers_async(): + client = ImageVersionsAsyncClient( + 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 = image_versions.ListImageVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse()) + await client.list_image_versions(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_image_versions_flattened(): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = image_versions.ListImageVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_image_versions( + 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_image_versions_flattened_error(): + client = ImageVersionsClient( + 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_image_versions( + image_versions.ListImageVersionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_image_versions_flattened_async(): + client = ImageVersionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = image_versions.ListImageVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_image_versions( + 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_image_versions_flattened_error_async(): + client = ImageVersionsAsyncClient( + 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_image_versions( + image_versions.ListImageVersionsRequest(), + parent='parent_value', + ) + + +def test_list_image_versions_pager(transport_name: str = "grpc"): + client = ImageVersionsClient( + 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_image_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + next_page_token='abc', + ), + image_versions.ListImageVersionsResponse( + image_versions=[], + next_page_token='def', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + ], + next_page_token='ghi', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_image_versions(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, image_versions.ImageVersion) + for i in results) +def test_list_image_versions_pages(transport_name: str = "grpc"): + client = ImageVersionsClient( + 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_image_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + next_page_token='abc', + ), + image_versions.ListImageVersionsResponse( + image_versions=[], + next_page_token='def', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + ], + next_page_token='ghi', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_image_versions(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_image_versions_async_pager(): + client = ImageVersionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + next_page_token='abc', + ), + image_versions.ListImageVersionsResponse( + image_versions=[], + next_page_token='def', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + ], + next_page_token='ghi', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_image_versions(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, image_versions.ImageVersion) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_image_versions_async_pages(): + client = ImageVersionsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + next_page_token='abc', + ), + image_versions.ListImageVersionsResponse( + image_versions=[], + next_page_token='def', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + ], + next_page_token='ghi', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + ), + 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_image_versions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_image_versions_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 = ImageVersionsClient( + 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_image_versions 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_image_versions] = mock_rpc + + request = {} + client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_image_versions(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_image_versions_rest_flattened(): + client = ImageVersionsClient( + 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 = image_versions.ListImageVersionsResponse() + + # 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 = image_versions.ListImageVersionsResponse.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_image_versions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*}/imageVersions" % client.transport._host, args[1]) + + +def test_list_image_versions_rest_flattened_error(transport: str = 'rest'): + client = ImageVersionsClient( + 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_image_versions( + image_versions.ListImageVersionsRequest(), + parent='parent_value', + ) + + +def test_list_image_versions_rest_pager(transport: str = 'rest'): + client = ImageVersionsClient( + 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 = ( + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + next_page_token='abc', + ), + image_versions.ListImageVersionsResponse( + image_versions=[], + next_page_token='def', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + ], + next_page_token='ghi', + ), + image_versions.ListImageVersionsResponse( + image_versions=[ + image_versions.ImageVersion(), + image_versions.ImageVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(image_versions.ListImageVersionsResponse.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_image_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, image_versions.ImageVersion) + for i in results) + + pages = list(client.list_image_versions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageVersionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ImageVersionsClient( + 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 = ImageVersionsClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageVersionsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ImageVersionsClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageVersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ImageVersionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ImageVersionsGrpcTransport, + transports.ImageVersionsGrpcAsyncIOTransport, + transports.ImageVersionsRestTransport, +]) +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 = ImageVersionsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ImageVersionsClient( + 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_list_image_versions_empty_call_grpc(): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + call.return_value = image_versions.ListImageVersionsResponse() + client.list_image_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = image_versions.ListImageVersionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ImageVersionsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ImageVersionsAsyncClient( + 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_list_image_versions_empty_call_grpc_asyncio(): + client = ImageVersionsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse( + next_page_token='next_page_token_value', + )) + await client.list_image_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = image_versions.ListImageVersionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ImageVersionsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_image_versions_rest_bad_request(request_type=image_versions.ListImageVersionsRequest): + client = ImageVersionsClient( + 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_image_versions(request) + + +@pytest.mark.parametrize("request_type", [ + image_versions.ListImageVersionsRequest, + dict, +]) +def test_list_image_versions_rest_call_success(request_type): + client = ImageVersionsClient( + 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 = image_versions.ListImageVersionsResponse( + 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 = image_versions.ListImageVersionsResponse.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_image_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImageVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_image_versions_rest_interceptors(null_interceptor): + transport = transports.ImageVersionsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ImageVersionsRestInterceptor(), + ) + client = ImageVersionsClient(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.ImageVersionsRestInterceptor, "post_list_image_versions") as post, \ + mock.patch.object(transports.ImageVersionsRestInterceptor, "post_list_image_versions_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ImageVersionsRestInterceptor, "pre_list_image_versions") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = image_versions.ListImageVersionsRequest.pb(image_versions.ListImageVersionsRequest()) + 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 = image_versions.ListImageVersionsResponse.to_json(image_versions.ListImageVersionsResponse()) + req.return_value.content = return_value + + request = image_versions.ListImageVersionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = image_versions.ListImageVersionsResponse() + post_with_metadata.return_value = image_versions.ListImageVersionsResponse(), metadata + + client.list_image_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = ImageVersionsClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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_list_image_versions_empty_call_rest(): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + client.list_image_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = image_versions.ListImageVersionsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ImageVersionsGrpcTransport, + ) + +def test_image_versions_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ImageVersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_image_versions_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.orchestration.airflow.service_v1beta1.services.image_versions.transports.ImageVersionsTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ImageVersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_image_versions', + 'get_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_image_versions_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.orchestration.airflow.service_v1beta1.services.image_versions.transports.ImageVersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageVersionsTransport( + 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_image_versions_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.orchestration.airflow.service_v1beta1.services.image_versions.transports.ImageVersionsTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageVersionsTransport() + adc.assert_called_once() + + +def test_image_versions_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) + ImageVersionsClient() + 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.ImageVersionsGrpcTransport, + transports.ImageVersionsGrpcAsyncIOTransport, + ], +) +def test_image_versions_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.ImageVersionsGrpcTransport, + transports.ImageVersionsGrpcAsyncIOTransport, + transports.ImageVersionsRestTransport, + ], +) +def test_image_versions_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.ImageVersionsGrpcTransport, grpc_helpers), + (transports.ImageVersionsGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_image_versions_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( + "composer.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="composer.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) +def test_image_versions_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_image_versions_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.ImageVersionsRestTransport ( + 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_image_versions_host_no_port(transport_name): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'composer.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://composer.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_image_versions_host_with_port(transport_name): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'composer.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://composer.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_image_versions_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ImageVersionsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ImageVersionsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_image_versions._session + session2 = client2.transport.list_image_versions._session + assert session1 != session2 +def test_image_versions_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ImageVersionsGrpcTransport( + 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_image_versions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ImageVersionsGrpcAsyncIOTransport( + 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.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) +def test_image_versions_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.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) +def test_image_versions_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_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ImageVersionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ImageVersionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ImageVersionsClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = ImageVersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ImageVersionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ImageVersionsClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ImageVersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ImageVersionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ImageVersionsClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = ImageVersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ImageVersionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ImageVersionsClient.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 = ImageVersionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ImageVersionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ImageVersionsClient.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.ImageVersionsTransport, '_prep_wrapped_messages') as prep: + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ImageVersionsTransport, '_prep_wrapped_messages') as prep: + transport_class = ImageVersionsClient.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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsAsyncClient( + 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 = ImageVersionsClient( + 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 = ImageVersionsClient( + 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", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport), + (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport), +]) +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 629a57df0274fe18e21efcfebc6a7e02a7acf170 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Sat, 15 Mar 2025 03:00:34 +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 - .../v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../v1/README.rst | 143 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../v1/docs/index.rst | 7 - .../v1/docs/service_v1/environments.rst | 10 - .../v1/docs/service_v1/image_versions.rst | 10 - .../v1/docs/service_v1/services_.rst | 7 - .../v1/docs/service_v1/types_.rst | 6 - .../orchestration/airflow/service/__init__.py | 159 - .../airflow/service/gapic_version.py | 16 - .../orchestration/airflow/service/py.typed | 2 - .../airflow/service_v1/__init__.py | 160 - .../airflow/service_v1/gapic_metadata.json | 422 - .../airflow/service_v1/gapic_version.py | 16 - .../orchestration/airflow/service_v1/py.typed | 2 - .../airflow/service_v1/services/__init__.py | 15 - .../services/environments/__init__.py | 22 - .../services/environments/async_client.py | 3216 --- .../services/environments/client.py | 3589 ---- .../services/environments/pagers.py | 583 - .../environments/transports/README.rst | 9 - .../environments/transports/__init__.py | 38 - .../services/environments/transports/base.py | 526 - .../services/environments/transports/grpc.py | 1070 - .../environments/transports/grpc_asyncio.py | 1220 -- .../services/environments/transports/rest.py | 4687 ---- .../environments/transports/rest_base.py | 1082 - .../services/image_versions/__init__.py | 22 - .../services/image_versions/async_client.py | 536 - .../services/image_versions/client.py | 897 - .../services/image_versions/pagers.py | 166 - .../image_versions/transports/README.rst | 9 - .../image_versions/transports/__init__.py | 38 - .../image_versions/transports/base.py | 197 - .../image_versions/transports/grpc.py | 402 - .../image_versions/transports/grpc_asyncio.py | 437 - .../image_versions/transports/rest.py | 742 - .../image_versions/transports/rest_base.py | 196 - .../airflow/service_v1/types/__init__.py | 152 - .../airflow/service_v1/types/environments.py | 3089 --- .../service_v1/types/image_versions.py | 148 - .../airflow/service_v1/types/operations.py | 147 - .../v1/mypy.ini | 3 - .../v1/noxfile.py | 280 - ...erated_environments_check_upgrade_async.py | 56 - ...nerated_environments_check_upgrade_sync.py | 56 - ...d_environments_create_environment_async.py | 55 - ...ed_environments_create_environment_sync.py | 55 - ..._create_user_workloads_config_map_async.py | 52 - ...s_create_user_workloads_config_map_sync.py | 52 - ...ents_create_user_workloads_secret_async.py | 52 - ...ments_create_user_workloads_secret_sync.py | 52 - ...ed_environments_database_failover_async.py | 55 - ...ted_environments_database_failover_sync.py | 55 - ...d_environments_delete_environment_async.py | 55 - ...ed_environments_delete_environment_sync.py | 55 - ..._delete_user_workloads_config_map_async.py | 50 - ...s_delete_user_workloads_config_map_sync.py | 50 - ...ents_delete_user_workloads_secret_async.py | 50 - ...ments_delete_user_workloads_secret_sync.py | 50 - ...ironments_execute_airflow_command_async.py | 51 - ...vironments_execute_airflow_command_sync.py | 51 - ...onments_fetch_database_properties_async.py | 52 - ...ronments_fetch_database_properties_sync.py | 52 - ...ated_environments_get_environment_async.py | 51 - ...rated_environments_get_environment_sync.py | 51 - ...nts_get_user_workloads_config_map_async.py | 52 - ...ents_get_user_workloads_config_map_sync.py | 52 - ...onments_get_user_workloads_secret_async.py | 52 - ...ronments_get_user_workloads_secret_sync.py | 52 - ...ed_environments_list_environments_async.py | 52 - ...ted_environments_list_environments_sync.py | 52 - ...s_list_user_workloads_config_maps_async.py | 53 - ...ts_list_user_workloads_config_maps_sync.py | 53 - ...ments_list_user_workloads_secrets_async.py | 53 - ...nments_list_user_workloads_secrets_sync.py | 53 - ...rated_environments_list_workloads_async.py | 53 - ...erated_environments_list_workloads_sync.py | 53 - ...erated_environments_load_snapshot_async.py | 55 - ...nerated_environments_load_snapshot_sync.py | 55 - ...environments_poll_airflow_command_async.py | 51 - ..._environments_poll_airflow_command_sync.py | 51 - ...erated_environments_save_snapshot_async.py | 55 - ...nerated_environments_save_snapshot_sync.py | 55 - ...environments_stop_airflow_command_async.py | 51 - ..._environments_stop_airflow_command_sync.py | 51 - ...d_environments_update_environment_async.py | 55 - ...ed_environments_update_environment_sync.py | 55 - ..._update_user_workloads_config_map_async.py | 51 - ...s_update_user_workloads_config_map_sync.py | 51 - ...ents_update_user_workloads_secret_async.py | 51 - ...ments_update_user_workloads_secret_sync.py | 51 - ...mage_versions_list_image_versions_async.py | 52 - ...image_versions_list_image_versions_sync.py | 52 - ...loud.orchestration.airflow.service.v1.json | 4004 ---- .../v1/scripts/fixup_service_v1_keywords.py | 200 - .../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 - .../tests/unit/gapic/service_v1/__init__.py | 16 - .../gapic/service_v1/test_environments.py | 17371 --------------- .../gapic/service_v1/test_image_versions.py | 2847 --- .../v1beta1/.coveragerc | 13 - .../v1beta1/.flake8 | 33 - .../v1beta1/MANIFEST.in | 2 - .../v1beta1/README.rst | 143 - .../v1beta1/airflow-service-v1beta1-py.tar.gz | 0 .../v1beta1/docs/_static/custom.css | 3 - .../v1beta1/docs/conf.py | 376 - .../v1beta1/docs/index.rst | 7 - .../docs/service_v1beta1/environments.rst | 10 - .../docs/service_v1beta1/image_versions.rst | 10 - .../docs/service_v1beta1/services_.rst | 7 - .../v1beta1/docs/service_v1beta1/types_.rst | 6 - .../orchestration/airflow/service/__init__.py | 161 - .../airflow/service/gapic_version.py | 16 - .../orchestration/airflow/service/py.typed | 2 - .../airflow/service_v1beta1/__init__.py | 162 - .../service_v1beta1/gapic_metadata.json | 437 - .../airflow/service_v1beta1/gapic_version.py | 16 - .../airflow/service_v1beta1/py.typed | 2 - .../service_v1beta1/services/__init__.py | 15 - .../services/environments/__init__.py | 22 - .../services/environments/async_client.py | 3350 --- .../services/environments/client.py | 3723 ---- .../services/environments/pagers.py | 583 - .../environments/transports/README.rst | 9 - .../environments/transports/__init__.py | 38 - .../services/environments/transports/base.py | 540 - .../services/environments/transports/grpc.py | 1096 - .../environments/transports/grpc_asyncio.py | 1251 -- .../services/environments/transports/rest.py | 4862 ----- .../environments/transports/rest_base.py | 1121 - .../services/image_versions/__init__.py | 22 - .../services/image_versions/async_client.py | 536 - .../services/image_versions/client.py | 897 - .../services/image_versions/pagers.py | 166 - .../image_versions/transports/README.rst | 9 - .../image_versions/transports/__init__.py | 38 - .../image_versions/transports/base.py | 197 - .../image_versions/transports/grpc.py | 402 - .../image_versions/transports/grpc_asyncio.py | 437 - .../image_versions/transports/rest.py | 742 - .../image_versions/transports/rest_base.py | 196 - .../airflow/service_v1beta1/types/__init__.py | 154 - .../service_v1beta1/types/environments.py | 3162 --- .../service_v1beta1/types/image_versions.py | 148 - .../service_v1beta1/types/operations.py | 143 - .../v1beta1/mypy.ini | 3 - .../v1beta1/noxfile.py | 280 - ...erated_environments_check_upgrade_async.py | 55 - ...nerated_environments_check_upgrade_sync.py | 55 - ...d_environments_create_environment_async.py | 55 - ...ed_environments_create_environment_sync.py | 55 - ..._create_user_workloads_config_map_async.py | 52 - ...s_create_user_workloads_config_map_sync.py | 52 - ...ents_create_user_workloads_secret_async.py | 52 - ...ments_create_user_workloads_secret_sync.py | 52 - ...ed_environments_database_failover_async.py | 55 - ...ted_environments_database_failover_sync.py | 55 - ...d_environments_delete_environment_async.py | 55 - ...ed_environments_delete_environment_sync.py | 55 - ..._delete_user_workloads_config_map_async.py | 50 - ...s_delete_user_workloads_config_map_sync.py | 50 - ...ents_delete_user_workloads_secret_async.py | 50 - ...ments_delete_user_workloads_secret_sync.py | 50 - ...ironments_execute_airflow_command_async.py | 51 - ...vironments_execute_airflow_command_sync.py | 51 - ...onments_fetch_database_properties_async.py | 52 - ...ronments_fetch_database_properties_sync.py | 52 - ...ated_environments_get_environment_async.py | 51 - ...rated_environments_get_environment_sync.py | 51 - ...nts_get_user_workloads_config_map_async.py | 52 - ...ents_get_user_workloads_config_map_sync.py | 52 - ...onments_get_user_workloads_secret_async.py | 52 - ...ronments_get_user_workloads_secret_sync.py | 52 - ...ed_environments_list_environments_async.py | 52 - ...ted_environments_list_environments_sync.py | 52 - ...s_list_user_workloads_config_maps_async.py | 53 - ...ts_list_user_workloads_config_maps_sync.py | 53 - ...ments_list_user_workloads_secrets_async.py | 53 - ...nments_list_user_workloads_secrets_sync.py | 53 - ...rated_environments_list_workloads_async.py | 53 - ...erated_environments_list_workloads_sync.py | 53 - ...erated_environments_load_snapshot_async.py | 55 - ...nerated_environments_load_snapshot_sync.py | 55 - ...environments_poll_airflow_command_async.py | 51 - ..._environments_poll_airflow_command_sync.py | 51 - ...d_environments_restart_web_server_async.py | 55 - ...ed_environments_restart_web_server_sync.py | 55 - ...erated_environments_save_snapshot_async.py | 55 - ...nerated_environments_save_snapshot_sync.py | 55 - ...environments_stop_airflow_command_async.py | 51 - ..._environments_stop_airflow_command_sync.py | 51 - ...d_environments_update_environment_async.py | 55 - ...ed_environments_update_environment_sync.py | 55 - ..._update_user_workloads_config_map_async.py | 51 - ...s_update_user_workloads_config_map_sync.py | 51 - ...ents_update_user_workloads_secret_async.py | 51 - ...ments_update_user_workloads_secret_sync.py | 51 - ...mage_versions_list_image_versions_async.py | 52 - ...image_versions_list_image_versions_sync.py | 52 - ...orchestration.airflow.service.v1beta1.json | 4157 ---- .../scripts/fixup_service_v1beta1_keywords.py | 201 - .../v1beta1/setup.py | 98 - .../v1beta1/testing/constraints-3.10.txt | 6 - .../v1beta1/testing/constraints-3.11.txt | 6 - .../v1beta1/testing/constraints-3.12.txt | 6 - .../v1beta1/testing/constraints-3.13.txt | 6 - .../v1beta1/testing/constraints-3.7.txt | 10 - .../v1beta1/testing/constraints-3.8.txt | 6 - .../v1beta1/testing/constraints-3.9.txt | 6 - .../v1beta1/tests/__init__.py | 16 - .../v1beta1/tests/unit/__init__.py | 16 - .../v1beta1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/service_v1beta1/__init__.py | 16 - .../service_v1beta1/test_environments.py | 17816 ---------------- .../service_v1beta1/test_image_versions.py | 2847 --- .../airflow-service-v1beta1-py.tar.gz | Bin 114688 -> 0 bytes .../services/environments/async_client.py | 22 +- .../services/environments/client.py | 22 +- .../services/environments/transports/grpc.py | 22 +- .../environments/transports/grpc_asyncio.py | 22 +- .../service_v1beta1/types/environments.py | 12 +- .../noxfile.py | 79 +- 236 files changed, 97 insertions(+), 105762 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/environments.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/image_versions.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/py.typed delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/async_client.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/pagers.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/image_versions.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/operations.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/README.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/airflow-service-v1beta1-py.tar.gz delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/environments.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/image_versions.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/py.typed delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/py.typed delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/async_client.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/pagers.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/image_versions.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_async.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_sync.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/setup.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py delete mode 100644 owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/.coveragerc b/owl-bot-staging/google-cloud-orchestration-airflow/v1/.coveragerc deleted file mode 100644 index 7b27e381927a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/orchestration/airflow/service/__init__.py - google/cloud/orchestration/airflow/service/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-orchestration-airflow/v1/.flake8 b/owl-bot-staging/google-cloud-orchestration-airflow/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/MANIFEST.in b/owl-bot-staging/google-cloud-orchestration-airflow/v1/MANIFEST.in deleted file mode 100644 index 0dfd92c7eac7..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/orchestration/airflow/service *.py -recursive-include google/cloud/orchestration/airflow/service_v1 *.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/README.rst deleted file mode 100644 index 4f24fd5ece7c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Cloud Orchestration Airflow Service 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 Orchestration Airflow Service 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 - - -Logging -------- - -This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. -Note the following: - -#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. -#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. -#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. - - -Simple, environment-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google -logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged -messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging -event. - -A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. - -- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. -- Invalid logging scopes: :code:`foo`, :code:`123`, etc. - -**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. - - -Examples -^^^^^^^^ - -- Enabling the default handler for all Google-based loggers - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google - -- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 - - -Advanced, code-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can also configure a valid logging scope using Python's standard `logging` mechanism. - - -Examples -^^^^^^^^ - -- Configuring a handler for all Google-based loggers - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - -- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google.cloud.library_v1") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - - -Logging details -~~~~~~~~~~~~~~~ - -#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root - logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set - :code:`logging.getLogger("google").propagate = True` in your code. -#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for - one library, but decide you need to also set up environment-based logging configuration for another library. - - #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual - if the code -based configuration gets applied first. - -#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get - executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. - (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/docs/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py deleted file mode 100644 index 0d6b253deba3..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow 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-orchestration-airflow" -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 Orchestration Airflow 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-orchestration-airflow-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-orchestration-airflow.tex", - u"google-cloud-orchestration-airflow 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-orchestration-airflow", - u"Google Cloud Orchestration Airflow Service 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-orchestration-airflow", - u"google-cloud-orchestration-airflow Documentation", - author, - "google-cloud-orchestration-airflow", - "GAPIC library for Google Cloud Orchestration Airflow Service 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-orchestration-airflow/v1/docs/index.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/index.rst deleted file mode 100644 index 728aa8ab3564..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - service_v1/services_ - service_v1/types_ diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/environments.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/environments.rst deleted file mode 100644 index b871d8d059ce..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/environments.rst +++ /dev/null @@ -1,10 +0,0 @@ -Environments ------------------------------- - -.. automodule:: google.cloud.orchestration.airflow.service_v1.services.environments - :members: - :inherited-members: - -.. automodule:: google.cloud.orchestration.airflow.service_v1.services.environments.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/image_versions.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/image_versions.rst deleted file mode 100644 index 8b2bcb1a902a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/image_versions.rst +++ /dev/null @@ -1,10 +0,0 @@ -ImageVersions -------------------------------- - -.. automodule:: google.cloud.orchestration.airflow.service_v1.services.image_versions - :members: - :inherited-members: - -.. automodule:: google.cloud.orchestration.airflow.service_v1.services.image_versions.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/services_.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/services_.rst deleted file mode 100644 index 0957e0c567a5..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/services_.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Orchestration Airflow Service v1 API -============================================================== -.. toctree:: - :maxdepth: 2 - - environments - image_versions diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/types_.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/types_.rst deleted file mode 100644 index b49b771a92a0..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/service_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Orchestration Airflow Service v1 API -=========================================================== - -.. automodule:: google.cloud.orchestration.airflow.service_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py deleted file mode 100644 index a031606b9262..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py +++ /dev/null @@ -1,159 +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.orchestration.airflow.service import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.orchestration.airflow.service_v1.services.environments.client import EnvironmentsClient -from google.cloud.orchestration.airflow.service_v1.services.environments.async_client import EnvironmentsAsyncClient -from google.cloud.orchestration.airflow.service_v1.services.image_versions.client import ImageVersionsClient -from google.cloud.orchestration.airflow.service_v1.services.image_versions.async_client import ImageVersionsAsyncClient - -from google.cloud.orchestration.airflow.service_v1.types.environments import AirflowMetadataRetentionPolicyConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import CheckUpgradeRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import CheckUpgradeResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import CloudDataLineageIntegration -from google.cloud.orchestration.airflow.service_v1.types.environments import CreateEnvironmentRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import CreateUserWorkloadsConfigMapRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import CreateUserWorkloadsSecretRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import DatabaseConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import DatabaseFailoverRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import DatabaseFailoverResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import DataRetentionConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import DeleteEnvironmentRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import DeleteUserWorkloadsConfigMapRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import DeleteUserWorkloadsSecretRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import EncryptionConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import Environment -from google.cloud.orchestration.airflow.service_v1.types.environments import EnvironmentConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import ExecuteAirflowCommandRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import ExecuteAirflowCommandResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import FetchDatabasePropertiesRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import FetchDatabasePropertiesResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import GetEnvironmentRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import GetUserWorkloadsConfigMapRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import GetUserWorkloadsSecretRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import IPAllocationPolicy -from google.cloud.orchestration.airflow.service_v1.types.environments import ListEnvironmentsRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import ListEnvironmentsResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import ListUserWorkloadsConfigMapsRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import ListUserWorkloadsConfigMapsResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import ListUserWorkloadsSecretsRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import ListUserWorkloadsSecretsResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import ListWorkloadsRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import ListWorkloadsResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import LoadSnapshotRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import LoadSnapshotResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import MaintenanceWindow -from google.cloud.orchestration.airflow.service_v1.types.environments import MasterAuthorizedNetworksConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import NetworkingConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import NodeConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import PollAirflowCommandRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import PollAirflowCommandResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import PrivateClusterConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import PrivateEnvironmentConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import RecoveryConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import SaveSnapshotRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import SaveSnapshotResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import ScheduledSnapshotsConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import SoftwareConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import StopAirflowCommandRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import StopAirflowCommandResponse -from google.cloud.orchestration.airflow.service_v1.types.environments import StorageConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import TaskLogsRetentionConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import UpdateEnvironmentRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import UpdateUserWorkloadsConfigMapRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import UpdateUserWorkloadsSecretRequest -from google.cloud.orchestration.airflow.service_v1.types.environments import UserWorkloadsConfigMap -from google.cloud.orchestration.airflow.service_v1.types.environments import UserWorkloadsSecret -from google.cloud.orchestration.airflow.service_v1.types.environments import WebServerConfig -from google.cloud.orchestration.airflow.service_v1.types.environments import WebServerNetworkAccessControl -from google.cloud.orchestration.airflow.service_v1.types.environments import WorkloadsConfig -from google.cloud.orchestration.airflow.service_v1.types.image_versions import ImageVersion -from google.cloud.orchestration.airflow.service_v1.types.image_versions import ListImageVersionsRequest -from google.cloud.orchestration.airflow.service_v1.types.image_versions import ListImageVersionsResponse -from google.cloud.orchestration.airflow.service_v1.types.operations import OperationMetadata - -__all__ = ('EnvironmentsClient', - 'EnvironmentsAsyncClient', - 'ImageVersionsClient', - 'ImageVersionsAsyncClient', - 'AirflowMetadataRetentionPolicyConfig', - 'CheckUpgradeRequest', - 'CheckUpgradeResponse', - 'CloudDataLineageIntegration', - 'CreateEnvironmentRequest', - 'CreateUserWorkloadsConfigMapRequest', - 'CreateUserWorkloadsSecretRequest', - 'DatabaseConfig', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'DataRetentionConfig', - 'DeleteEnvironmentRequest', - 'DeleteUserWorkloadsConfigMapRequest', - 'DeleteUserWorkloadsSecretRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'GetEnvironmentRequest', - 'GetUserWorkloadsConfigMapRequest', - 'GetUserWorkloadsSecretRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'ListUserWorkloadsConfigMapsRequest', - 'ListUserWorkloadsConfigMapsResponse', - 'ListUserWorkloadsSecretsRequest', - 'ListUserWorkloadsSecretsResponse', - 'ListWorkloadsRequest', - 'ListWorkloadsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'StorageConfig', - 'TaskLogsRetentionConfig', - 'UpdateEnvironmentRequest', - 'UpdateUserWorkloadsConfigMapRequest', - 'UpdateUserWorkloadsSecretRequest', - 'UserWorkloadsConfigMap', - 'UserWorkloadsSecret', - 'WebServerConfig', - 'WebServerNetworkAccessControl', - 'WorkloadsConfig', - 'ImageVersion', - 'ListImageVersionsRequest', - 'ListImageVersionsResponse', - 'OperationMetadata', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/gapic_version.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/py.typed b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/py.typed deleted file mode 100644 index f8ae386fb27e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-orchestration-airflow package uses inline types. diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py deleted file mode 100644 index b135afbc2b24..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py +++ /dev/null @@ -1,160 +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.orchestration.airflow.service_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.environments import EnvironmentsClient -from .services.environments import EnvironmentsAsyncClient -from .services.image_versions import ImageVersionsClient -from .services.image_versions import ImageVersionsAsyncClient - -from .types.environments import AirflowMetadataRetentionPolicyConfig -from .types.environments import CheckUpgradeRequest -from .types.environments import CheckUpgradeResponse -from .types.environments import CloudDataLineageIntegration -from .types.environments import CreateEnvironmentRequest -from .types.environments import CreateUserWorkloadsConfigMapRequest -from .types.environments import CreateUserWorkloadsSecretRequest -from .types.environments import DatabaseConfig -from .types.environments import DatabaseFailoverRequest -from .types.environments import DatabaseFailoverResponse -from .types.environments import DataRetentionConfig -from .types.environments import DeleteEnvironmentRequest -from .types.environments import DeleteUserWorkloadsConfigMapRequest -from .types.environments import DeleteUserWorkloadsSecretRequest -from .types.environments import EncryptionConfig -from .types.environments import Environment -from .types.environments import EnvironmentConfig -from .types.environments import ExecuteAirflowCommandRequest -from .types.environments import ExecuteAirflowCommandResponse -from .types.environments import FetchDatabasePropertiesRequest -from .types.environments import FetchDatabasePropertiesResponse -from .types.environments import GetEnvironmentRequest -from .types.environments import GetUserWorkloadsConfigMapRequest -from .types.environments import GetUserWorkloadsSecretRequest -from .types.environments import IPAllocationPolicy -from .types.environments import ListEnvironmentsRequest -from .types.environments import ListEnvironmentsResponse -from .types.environments import ListUserWorkloadsConfigMapsRequest -from .types.environments import ListUserWorkloadsConfigMapsResponse -from .types.environments import ListUserWorkloadsSecretsRequest -from .types.environments import ListUserWorkloadsSecretsResponse -from .types.environments import ListWorkloadsRequest -from .types.environments import ListWorkloadsResponse -from .types.environments import LoadSnapshotRequest -from .types.environments import LoadSnapshotResponse -from .types.environments import MaintenanceWindow -from .types.environments import MasterAuthorizedNetworksConfig -from .types.environments import NetworkingConfig -from .types.environments import NodeConfig -from .types.environments import PollAirflowCommandRequest -from .types.environments import PollAirflowCommandResponse -from .types.environments import PrivateClusterConfig -from .types.environments import PrivateEnvironmentConfig -from .types.environments import RecoveryConfig -from .types.environments import SaveSnapshotRequest -from .types.environments import SaveSnapshotResponse -from .types.environments import ScheduledSnapshotsConfig -from .types.environments import SoftwareConfig -from .types.environments import StopAirflowCommandRequest -from .types.environments import StopAirflowCommandResponse -from .types.environments import StorageConfig -from .types.environments import TaskLogsRetentionConfig -from .types.environments import UpdateEnvironmentRequest -from .types.environments import UpdateUserWorkloadsConfigMapRequest -from .types.environments import UpdateUserWorkloadsSecretRequest -from .types.environments import UserWorkloadsConfigMap -from .types.environments import UserWorkloadsSecret -from .types.environments import WebServerConfig -from .types.environments import WebServerNetworkAccessControl -from .types.environments import WorkloadsConfig -from .types.image_versions import ImageVersion -from .types.image_versions import ListImageVersionsRequest -from .types.image_versions import ListImageVersionsResponse -from .types.operations import OperationMetadata - -__all__ = ( - 'EnvironmentsAsyncClient', - 'ImageVersionsAsyncClient', -'AirflowMetadataRetentionPolicyConfig', -'CheckUpgradeRequest', -'CheckUpgradeResponse', -'CloudDataLineageIntegration', -'CreateEnvironmentRequest', -'CreateUserWorkloadsConfigMapRequest', -'CreateUserWorkloadsSecretRequest', -'DataRetentionConfig', -'DatabaseConfig', -'DatabaseFailoverRequest', -'DatabaseFailoverResponse', -'DeleteEnvironmentRequest', -'DeleteUserWorkloadsConfigMapRequest', -'DeleteUserWorkloadsSecretRequest', -'EncryptionConfig', -'Environment', -'EnvironmentConfig', -'EnvironmentsClient', -'ExecuteAirflowCommandRequest', -'ExecuteAirflowCommandResponse', -'FetchDatabasePropertiesRequest', -'FetchDatabasePropertiesResponse', -'GetEnvironmentRequest', -'GetUserWorkloadsConfigMapRequest', -'GetUserWorkloadsSecretRequest', -'IPAllocationPolicy', -'ImageVersion', -'ImageVersionsClient', -'ListEnvironmentsRequest', -'ListEnvironmentsResponse', -'ListImageVersionsRequest', -'ListImageVersionsResponse', -'ListUserWorkloadsConfigMapsRequest', -'ListUserWorkloadsConfigMapsResponse', -'ListUserWorkloadsSecretsRequest', -'ListUserWorkloadsSecretsResponse', -'ListWorkloadsRequest', -'ListWorkloadsResponse', -'LoadSnapshotRequest', -'LoadSnapshotResponse', -'MaintenanceWindow', -'MasterAuthorizedNetworksConfig', -'NetworkingConfig', -'NodeConfig', -'OperationMetadata', -'PollAirflowCommandRequest', -'PollAirflowCommandResponse', -'PrivateClusterConfig', -'PrivateEnvironmentConfig', -'RecoveryConfig', -'SaveSnapshotRequest', -'SaveSnapshotResponse', -'ScheduledSnapshotsConfig', -'SoftwareConfig', -'StopAirflowCommandRequest', -'StopAirflowCommandResponse', -'StorageConfig', -'TaskLogsRetentionConfig', -'UpdateEnvironmentRequest', -'UpdateUserWorkloadsConfigMapRequest', -'UpdateUserWorkloadsSecretRequest', -'UserWorkloadsConfigMap', -'UserWorkloadsSecret', -'WebServerConfig', -'WebServerNetworkAccessControl', -'WorkloadsConfig', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json deleted file mode 100644 index aca0f03a3f15..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json +++ /dev/null @@ -1,422 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.orchestration.airflow.service_v1", - "protoPackage": "google.cloud.orchestration.airflow.service.v1", - "schema": "1.0", - "services": { - "Environments": { - "clients": { - "grpc": { - "libraryClient": "EnvironmentsClient", - "rpcs": { - "CheckUpgrade": { - "methods": [ - "check_upgrade" - ] - }, - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "CreateUserWorkloadsConfigMap": { - "methods": [ - "create_user_workloads_config_map" - ] - }, - "CreateUserWorkloadsSecret": { - "methods": [ - "create_user_workloads_secret" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "DeleteUserWorkloadsConfigMap": { - "methods": [ - "delete_user_workloads_config_map" - ] - }, - "DeleteUserWorkloadsSecret": { - "methods": [ - "delete_user_workloads_secret" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "GetUserWorkloadsConfigMap": { - "methods": [ - "get_user_workloads_config_map" - ] - }, - "GetUserWorkloadsSecret": { - "methods": [ - "get_user_workloads_secret" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "ListUserWorkloadsConfigMaps": { - "methods": [ - "list_user_workloads_config_maps" - ] - }, - "ListUserWorkloadsSecrets": { - "methods": [ - "list_user_workloads_secrets" - ] - }, - "ListWorkloads": { - "methods": [ - "list_workloads" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - }, - "UpdateUserWorkloadsConfigMap": { - "methods": [ - "update_user_workloads_config_map" - ] - }, - "UpdateUserWorkloadsSecret": { - "methods": [ - "update_user_workloads_secret" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EnvironmentsAsyncClient", - "rpcs": { - "CheckUpgrade": { - "methods": [ - "check_upgrade" - ] - }, - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "CreateUserWorkloadsConfigMap": { - "methods": [ - "create_user_workloads_config_map" - ] - }, - "CreateUserWorkloadsSecret": { - "methods": [ - "create_user_workloads_secret" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "DeleteUserWorkloadsConfigMap": { - "methods": [ - "delete_user_workloads_config_map" - ] - }, - "DeleteUserWorkloadsSecret": { - "methods": [ - "delete_user_workloads_secret" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "GetUserWorkloadsConfigMap": { - "methods": [ - "get_user_workloads_config_map" - ] - }, - "GetUserWorkloadsSecret": { - "methods": [ - "get_user_workloads_secret" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "ListUserWorkloadsConfigMaps": { - "methods": [ - "list_user_workloads_config_maps" - ] - }, - "ListUserWorkloadsSecrets": { - "methods": [ - "list_user_workloads_secrets" - ] - }, - "ListWorkloads": { - "methods": [ - "list_workloads" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - }, - "UpdateUserWorkloadsConfigMap": { - "methods": [ - "update_user_workloads_config_map" - ] - }, - "UpdateUserWorkloadsSecret": { - "methods": [ - "update_user_workloads_secret" - ] - } - } - }, - "rest": { - "libraryClient": "EnvironmentsClient", - "rpcs": { - "CheckUpgrade": { - "methods": [ - "check_upgrade" - ] - }, - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "CreateUserWorkloadsConfigMap": { - "methods": [ - "create_user_workloads_config_map" - ] - }, - "CreateUserWorkloadsSecret": { - "methods": [ - "create_user_workloads_secret" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "DeleteUserWorkloadsConfigMap": { - "methods": [ - "delete_user_workloads_config_map" - ] - }, - "DeleteUserWorkloadsSecret": { - "methods": [ - "delete_user_workloads_secret" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "GetUserWorkloadsConfigMap": { - "methods": [ - "get_user_workloads_config_map" - ] - }, - "GetUserWorkloadsSecret": { - "methods": [ - "get_user_workloads_secret" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "ListUserWorkloadsConfigMaps": { - "methods": [ - "list_user_workloads_config_maps" - ] - }, - "ListUserWorkloadsSecrets": { - "methods": [ - "list_user_workloads_secrets" - ] - }, - "ListWorkloads": { - "methods": [ - "list_workloads" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - }, - "UpdateUserWorkloadsConfigMap": { - "methods": [ - "update_user_workloads_config_map" - ] - }, - "UpdateUserWorkloadsSecret": { - "methods": [ - "update_user_workloads_secret" - ] - } - } - } - } - }, - "ImageVersions": { - "clients": { - "grpc": { - "libraryClient": "ImageVersionsClient", - "rpcs": { - "ListImageVersions": { - "methods": [ - "list_image_versions" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ImageVersionsAsyncClient", - "rpcs": { - "ListImageVersions": { - "methods": [ - "list_image_versions" - ] - } - } - }, - "rest": { - "libraryClient": "ImageVersionsClient", - "rpcs": { - "ListImageVersions": { - "methods": [ - "list_image_versions" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_version.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/py.typed b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/py.typed deleted file mode 100644 index f8ae386fb27e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-orchestration-airflow package uses inline types. diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/__init__.py deleted file mode 100644 index 8aea3f820923..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/__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 EnvironmentsClient -from .async_client import EnvironmentsAsyncClient - -__all__ = ( - 'EnvironmentsClient', - 'EnvironmentsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py deleted file mode 100644 index f70a3fe39a6f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py +++ /dev/null @@ -1,3216 +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.orchestration.airflow.service_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.orchestration.airflow.service_v1.services.environments import pagers -from google.cloud.orchestration.airflow.service_v1.types import environments -from google.cloud.orchestration.airflow.service_v1.types import operations -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 EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .client import EnvironmentsClient - -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 EnvironmentsAsyncClient: - """Managed Apache Airflow Environments.""" - - _client: EnvironmentsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = EnvironmentsClient._DEFAULT_UNIVERSE - - environment_path = staticmethod(EnvironmentsClient.environment_path) - parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) - user_workloads_config_map_path = staticmethod(EnvironmentsClient.user_workloads_config_map_path) - parse_user_workloads_config_map_path = staticmethod(EnvironmentsClient.parse_user_workloads_config_map_path) - user_workloads_secret_path = staticmethod(EnvironmentsClient.user_workloads_secret_path) - parse_user_workloads_secret_path = staticmethod(EnvironmentsClient.parse_user_workloads_secret_path) - common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) - parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) - common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) - parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) - common_project_path = staticmethod(EnvironmentsClient.common_project_path) - parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) - common_location_path = staticmethod(EnvironmentsClient.common_location_path) - parse_common_location_path = staticmethod(EnvironmentsClient.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: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, 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: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, 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 EnvironmentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EnvironmentsTransport: - """Returns the transport used by the client instance. - - Returns: - EnvironmentsTransport: 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 = EnvironmentsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EnvironmentsTransport, Callable[..., EnvironmentsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the environments 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,EnvironmentsTransport,Callable[..., EnvironmentsTransport]]]): - 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 EnvironmentsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = EnvironmentsClient( - 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.orchestration.airflow.service_v1.EnvironmentsAsyncClient`.", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "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.orchestration.airflow.service.v1.Environments", - "credentialsType": None, - } - ) - - async def create_environment(self, - request: Optional[Union[environments.CreateEnvironmentRequest, dict]] = None, - *, - parent: Optional[str] = None, - environment: Optional[environments.Environment] = 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"""Create a new environment. - - .. 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.orchestration.airflow import service_v1 - - async def sample_create_environment(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.CreateEnvironmentRequest( - ) - - # Make the request - operation = client.create_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.CreateEnvironmentRequest, dict]]): - The request object. Create a new environment. - parent (:class:`str`): - The parent must be of the form - "projects/{projectId}/locations/{locationId}". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (:class:`google.cloud.orchestration.airflow.service_v1.types.Environment`): - The environment to create. - This corresponds to the ``environment`` 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.orchestration.airflow.service_v1.types.Environment` - An environment for running orchestration tasks. - - """ - # 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. - flattened_params = [parent, environment] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateEnvironmentRequest): - request = environments.CreateEnvironmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if environment is not None: - request.environment = environment - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_environment] - - # 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, - environments.Environment, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_environment(self, - request: Optional[Union[environments.GetEnvironmentRequest, 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]]] = (), - ) -> environments.Environment: - r"""Get an existing environment. - - .. 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.orchestration.airflow import service_v1 - - async def sample_get_environment(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.GetEnvironmentRequest( - ) - - # Make the request - response = await client.get_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.GetEnvironmentRequest, dict]]): - The request object. Get an environment. - name (:class:`str`): - The resource name of the environment - to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1.types.Environment: - An environment for running - orchestration tasks. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetEnvironmentRequest): - request = environments.GetEnvironmentRequest(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_environment] - - # 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_environments(self, - request: Optional[Union[environments.ListEnvironmentsRequest, 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.ListEnvironmentsAsyncPager: - r"""List environments. - - .. 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.orchestration.airflow import service_v1 - - async def sample_list_environments(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ListEnvironmentsRequest( - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest, dict]]): - The request object. List environments in a project and - location. - parent (:class:`str`): - List environments in the given - project and location, in the form: - "projects/{projectId}/locations/{locationId}" - - 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.orchestration.airflow.service_v1.services.environments.pagers.ListEnvironmentsAsyncPager: - The environments in a project and - location. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListEnvironmentsRequest): - request = environments.ListEnvironmentsRequest(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_environments] - - # 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.ListEnvironmentsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_environment(self, - request: Optional[Union[environments.UpdateEnvironmentRequest, dict]] = None, - *, - name: Optional[str] = None, - environment: Optional[environments.Environment] = 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"""Update an environment. - - .. 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.orchestration.airflow import service_v1 - - async def sample_update_environment(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.UpdateEnvironmentRequest( - ) - - # Make the request - operation = client.update_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.UpdateEnvironmentRequest, dict]]): - The request object. Update an environment. - name (:class:`str`): - The relative resource name of the - environment to update, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (:class:`google.cloud.orchestration.airflow.service_v1.types.Environment`): - A patch environment. Fields specified by the - ``updateMask`` will be copied from the patch environment - into the environment under update. - - This corresponds to the ``environment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. A comma-separated list of paths, relative to - ``Environment``, of fields to update. For example, to - set the version of scikit-learn to install in the - environment to 0.19.0 and to remove an existing - installation of numpy, the ``updateMask`` parameter - would include the following two ``paths`` values: - "config.softwareConfig.pypiPackages.scikit-learn" and - "config.softwareConfig.pypiPackages.numpy". The included - patch environment would specify the scikit-learn version - as follows: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "scikit-learn":"==0.19.0" - } - } - } - } - - Note that in the above example, any existing PyPI - packages other than scikit-learn and numpy will be - unaffected. - - Only one update type may be included in a single - request's ``updateMask``. For example, one cannot update - both the PyPI packages and labels in the same request. - However, it is possible to update multiple members of a - map field simultaneously in the same request. For - example, to set the labels "label1" and "label2" while - clearing "label3" (assuming it already exists), one can - provide the paths "labels.label1", "labels.label2", and - "labels.label3" and populate the patch environment as - follows: - - :: - - { - "labels":{ - "label1":"new-label1-value" - "label2":"new-label2-value" - } - } - - Note that in the above example, any existing labels that - are not included in the ``updateMask`` will be - unaffected. - - It is also possible to replace an entire map field by - providing the map field's path in the ``updateMask``. - The new value of the field will be that which is - provided in the patch environment. For example, to - delete all pre-existing user-specified PyPI packages and - install botocore at version 1.7.14, the ``updateMask`` - would contain the path - "config.softwareConfig.pypiPackages", and the patch - environment would be the following: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "botocore":"==1.7.14" - } - } - } - } - - **Note:** Only the following fields can be updated: - - - ``config.softwareConfig.pypiPackages`` - - - Replace all custom custom PyPI packages. If a - replacement package map is not included in - ``environment``, all custom PyPI packages are - cleared. It is an error to provide both this mask - and a mask specifying an individual package. - - - ``config.softwareConfig.pypiPackages.``\ packagename - - - Update the custom PyPI package *packagename*, - preserving other packages. To delete the package, - include it in ``updateMask``, and omit the mapping - for it in - ``environment.config.softwareConfig.pypiPackages``. - It is an error to provide both a mask of this form - and the ``config.softwareConfig.pypiPackages`` - mask. - - - ``labels`` - - - Replace all environment labels. If a replacement - labels map is not included in ``environment``, all - labels are cleared. It is an error to provide both - this mask and a mask specifying one or more - individual labels. - - - ``labels.``\ labelName - - - Set the label named *labelName*, while preserving - other labels. To delete the label, include it in - ``updateMask`` and omit its mapping in - ``environment.labels``. It is an error to provide - both a mask of this form and the ``labels`` mask. - - - ``config.nodeCount`` - - - Horizontally scale the number of nodes in the - environment. An integer greater than or equal to 3 - must be provided in the ``config.nodeCount`` - field. Supported for Cloud Composer environments - in versions composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerNetworkAccessControl`` - - - Replace the environment's current - ``WebServerNetworkAccessControl``. - - - ``config.softwareConfig.airflowConfigOverrides`` - - - Replace all Apache Airflow config overrides. If a - replacement config overrides map is not included - in ``environment``, all config overrides are - cleared. It is an error to provide both this mask - and a mask specifying one or more individual - config overrides. - - - ``config.softwareConfig.airflowConfigOverrides.``\ section-name - - - Override the Apache Airflow config property *name* - in the section named *section*, preserving other - properties. To delete the property override, - include it in ``updateMask`` and omit its mapping - in - ``environment.config.softwareConfig.airflowConfigOverrides``. - It is an error to provide both a mask of this form - and the - ``config.softwareConfig.airflowConfigOverrides`` - mask. - - - ``config.softwareConfig.envVariables`` - - - Replace all environment variables. If a - replacement environment variable map is not - included in ``environment``, all custom - environment variables are cleared. - - - ``config.softwareConfig.schedulerCount`` - - - Horizontally scale the number of schedulers in - Airflow. A positive integer not greater than the - number of nodes must be provided in the - ``config.softwareConfig.schedulerCount`` field. - Supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-2.*.*. - - - ``config.databaseConfig.machineType`` - - - Cloud SQL machine type used by Airflow database. - It has to be one of: db-n1-standard-2, - db-n1-standard-4, db-n1-standard-8 or - db-n1-standard-16. Supported for Cloud Composer - environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerConfig.machineType`` - - - Machine type on which Airflow web server is - running. It has to be one of: - composer-n1-webserver-2, composer-n1-webserver-4 - or composer-n1-webserver-8. Supported for Cloud - Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - 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.orchestration.airflow.service_v1.types.Environment` - An environment for running orchestration tasks. - - """ - # 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. - flattened_params = [name, environment, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateEnvironmentRequest): - request = environments.UpdateEnvironmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if environment is not None: - request.environment = environment - 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_environment] - - # 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, - environments.Environment, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_environment(self, - request: Optional[Union[environments.DeleteEnvironmentRequest, 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"""Delete an environment. - - .. 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.orchestration.airflow import service_v1 - - async def sample_delete_environment(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.DeleteEnvironmentRequest( - ) - - # Make the request - operation = client.delete_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.DeleteEnvironmentRequest, dict]]): - The request object. Delete an environment. - name (:class:`str`): - The environment to delete, in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteEnvironmentRequest): - request = environments.DeleteEnvironmentRequest(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_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def execute_airflow_command(self, - request: Optional[Union[environments.ExecuteAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.ExecuteAirflowCommandResponse: - r"""Executes Airflow CLI command. - - .. 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.orchestration.airflow import service_v1 - - async def sample_execute_airflow_command(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ExecuteAirflowCommandRequest( - ) - - # Make the request - response = await client.execute_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandRequest, dict]]): - The request object. Execute Airflow Command request. - 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.orchestration.airflow.service_v1.types.ExecuteAirflowCommandResponse: - Response to - ExecuteAirflowCommandRequest. - - """ - # 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, environments.ExecuteAirflowCommandRequest): - request = environments.ExecuteAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.execute_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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 stop_airflow_command(self, - request: Optional[Union[environments.StopAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.StopAirflowCommandResponse: - r"""Stops Airflow CLI command execution. - - .. 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.orchestration.airflow import service_v1 - - async def sample_stop_airflow_command(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.StopAirflowCommandRequest( - ) - - # Make the request - response = await client.stop_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandRequest, dict]]): - The request object. Stop Airflow Command request. - 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.orchestration.airflow.service_v1.types.StopAirflowCommandResponse: - Response to - StopAirflowCommandRequest. - - """ - # 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, environments.StopAirflowCommandRequest): - request = environments.StopAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.stop_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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 poll_airflow_command(self, - request: Optional[Union[environments.PollAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.PollAirflowCommandResponse: - r"""Polls Airflow CLI command execution and fetches logs. - - .. 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.orchestration.airflow import service_v1 - - async def sample_poll_airflow_command(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.PollAirflowCommandRequest( - ) - - # Make the request - response = await client.poll_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandRequest, dict]]): - The request object. Poll Airflow Command request. - 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.orchestration.airflow.service_v1.types.PollAirflowCommandResponse: - Response to - PollAirflowCommandRequest. - - """ - # 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, environments.PollAirflowCommandRequest): - request = environments.PollAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.poll_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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_workloads(self, - request: Optional[Union[environments.ListWorkloadsRequest, 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.ListWorkloadsAsyncPager: - r"""Lists workloads in a Cloud Composer environment. Workload is a - unit that runs a single Composer component. - - This method is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_list_workloads(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ListWorkloadsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workloads(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest, dict]]): - The request object. Request for listing workloads in a - Cloud Composer environment. - parent (:class:`str`): - Required. The environment name to get - workloads for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1.services.environments.pagers.ListWorkloadsAsyncPager: - Response to ListWorkloadsRequest. - - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListWorkloadsRequest): - request = environments.ListWorkloadsRequest(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_workloads] - - # 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.ListWorkloadsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def check_upgrade(self, - request: Optional[Union[environments.CheckUpgradeRequest, dict]] = 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"""Check if an upgrade operation on the environment will - succeed. - In case of problems detailed info can be found in the - returned 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.orchestration.airflow import service_v1 - - async def sample_check_upgrade(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.CheckUpgradeRequest( - environment="environment_value", - ) - - # Make the request - operation = client.check_upgrade(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.CheckUpgradeRequest, dict]]): - The request object. Request to check whether image - upgrade will succeed. - 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.orchestration.airflow.service_v1.types.CheckUpgradeResponse` Message containing information about the result of an upgrade check - operation. - - """ - # 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, environments.CheckUpgradeRequest): - request = environments.CheckUpgradeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.check_upgrade] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.CheckUpgradeResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def create_user_workloads_secret(self, - request: Optional[Union[environments.CreateUserWorkloadsSecretRequest, dict]] = None, - *, - parent: Optional[str] = None, - user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_create_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.CreateUserWorkloadsSecretRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsSecretRequest, dict]]): - The request object. Create user workloads Secret request. - parent (:class:`str`): - Required. The environment name to - create a Secret for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_workloads_secret (:class:`google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret`): - Required. User workloads Secret to - create. - - This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [parent, user_workloads_secret] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateUserWorkloadsSecretRequest): - request = environments.CreateUserWorkloadsSecretRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_workloads_secret is not None: - request.user_workloads_secret = user_workloads_secret - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_user_workloads_secret] - - # 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 get_user_workloads_secret(self, - request: Optional[Union[environments.GetUserWorkloadsSecretRequest, 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]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Gets an existing user workloads Secret. Values of the "data" - field in the response are cleared. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_get_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.GetUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsSecretRequest, dict]]): - The request object. Get user workloads Secret request. - name (:class:`str`): - Required. The resource name of the - Secret to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" - - 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetUserWorkloadsSecretRequest): - request = environments.GetUserWorkloadsSecretRequest(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_user_workloads_secret] - - # 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_user_workloads_secrets(self, - request: Optional[Union[environments.ListUserWorkloadsSecretsRequest, 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.ListUserWorkloadsSecretsAsyncPager: - r"""Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_list_user_workloads_secrets(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ListUserWorkloadsSecretsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_secrets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest, dict]]): - The request object. List user workloads Secrets request. - parent (:class:`str`): - Required. List Secrets in the given - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsSecretsAsyncPager: - The user workloads Secrets for a - given environment. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListUserWorkloadsSecretsRequest): - request = environments.ListUserWorkloadsSecretsRequest(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_user_workloads_secrets] - - # 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.ListUserWorkloadsSecretsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_user_workloads_secret(self, - request: Optional[Union[environments.UpdateUserWorkloadsSecretRequest, dict]] = None, - *, - user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_update_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.UpdateUserWorkloadsSecretRequest( - ) - - # Make the request - response = await client.update_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsSecretRequest, dict]]): - The request object. Update user workloads Secret request. - user_workloads_secret (:class:`google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret`): - Optional. User workloads Secret to - override. - - This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [user_workloads_secret] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateUserWorkloadsSecretRequest): - request = environments.UpdateUserWorkloadsSecretRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if user_workloads_secret is not None: - request.user_workloads_secret = user_workloads_secret - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_user_workloads_secret] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user_workloads_secret.name", request.user_workloads_secret.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_user_workloads_secret(self, - request: Optional[Union[environments.DeleteUserWorkloadsSecretRequest, 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]]] = (), - ) -> None: - r"""Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_delete_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.DeleteUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - await client.delete_user_workloads_secret(request=request) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsSecretRequest, dict]]): - The request object. Delete user workloads Secret request. - name (:class:`str`): - Required. The Secret to delete, in - the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" - - 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`. - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteUserWorkloadsSecretRequest): - request = environments.DeleteUserWorkloadsSecretRequest(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_user_workloads_secret] - - # 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 create_user_workloads_config_map(self, - request: Optional[Union[environments.CreateUserWorkloadsConfigMapRequest, dict]] = None, - *, - parent: Optional[str] = None, - user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_create_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.CreateUserWorkloadsConfigMapRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsConfigMapRequest, dict]]): - The request object. Create user workloads ConfigMap - request. - parent (:class:`str`): - Required. The environment name to - create a ConfigMap for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_workloads_config_map (:class:`google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap`): - Required. User workloads ConfigMap to - create. - - This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [parent, user_workloads_config_map] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateUserWorkloadsConfigMapRequest): - request = environments.CreateUserWorkloadsConfigMapRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_workloads_config_map is not None: - request.user_workloads_config_map = user_workloads_config_map - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_user_workloads_config_map] - - # 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 get_user_workloads_config_map(self, - request: Optional[Union[environments.GetUserWorkloadsConfigMapRequest, 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]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_get_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.GetUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsConfigMapRequest, dict]]): - The request object. Get user workloads ConfigMap request. - name (:class:`str`): - Required. The resource name of the - ConfigMap to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" - - 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetUserWorkloadsConfigMapRequest): - request = environments.GetUserWorkloadsConfigMapRequest(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_user_workloads_config_map] - - # 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_user_workloads_config_maps(self, - request: Optional[Union[environments.ListUserWorkloadsConfigMapsRequest, 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.ListUserWorkloadsConfigMapsAsyncPager: - r"""Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_list_user_workloads_config_maps(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ListUserWorkloadsConfigMapsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_config_maps(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest, dict]]): - The request object. List user workloads ConfigMaps - request. - parent (:class:`str`): - Required. List ConfigMaps in the - given environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsConfigMapsAsyncPager: - The user workloads ConfigMaps for a - given environment. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListUserWorkloadsConfigMapsRequest): - request = environments.ListUserWorkloadsConfigMapsRequest(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_user_workloads_config_maps] - - # 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.ListUserWorkloadsConfigMapsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_user_workloads_config_map(self, - request: Optional[Union[environments.UpdateUserWorkloadsConfigMapRequest, dict]] = None, - *, - user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_update_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.UpdateUserWorkloadsConfigMapRequest( - ) - - # Make the request - response = await client.update_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsConfigMapRequest, dict]]): - The request object. Update user workloads ConfigMap - request. - user_workloads_config_map (:class:`google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap`): - Optional. User workloads ConfigMap to - override. - - This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [user_workloads_config_map] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateUserWorkloadsConfigMapRequest): - request = environments.UpdateUserWorkloadsConfigMapRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if user_workloads_config_map is not None: - request.user_workloads_config_map = user_workloads_config_map - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_user_workloads_config_map] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user_workloads_config_map.name", request.user_workloads_config_map.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_user_workloads_config_map(self, - request: Optional[Union[environments.DeleteUserWorkloadsConfigMapRequest, 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]]] = (), - ) -> None: - r"""Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - async def sample_delete_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.DeleteUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - await client.delete_user_workloads_config_map(request=request) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsConfigMapRequest, dict]]): - The request object. Delete user workloads ConfigMap - request. - name (:class:`str`): - Required. The ConfigMap to delete, in - the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" - - 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`. - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteUserWorkloadsConfigMapRequest): - request = environments.DeleteUserWorkloadsConfigMapRequest(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_user_workloads_config_map] - - # 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 save_snapshot(self, - request: Optional[Union[environments.SaveSnapshotRequest, dict]] = 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 snapshots of a Cloud Composer environment. - - As a result of this operation, snapshot of environment's - state is stored in a location specified in the - SaveSnapshotRequest. - - .. 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.orchestration.airflow import service_v1 - - async def sample_save_snapshot(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.SaveSnapshotRequest( - ) - - # Make the request - operation = client.save_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.SaveSnapshotRequest, dict]]): - The request object. Request to create a snapshot of a - Cloud Composer environment. - 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.orchestration.airflow.service_v1.types.SaveSnapshotResponse` - Response to SaveSnapshotRequest. - - """ - # 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, environments.SaveSnapshotRequest): - request = environments.SaveSnapshotRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.save_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.SaveSnapshotResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def load_snapshot(self, - request: Optional[Union[environments.LoadSnapshotRequest, dict]] = 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"""Loads a snapshot of a Cloud Composer environment. - - As a result of this operation, a snapshot of - environment's specified in LoadSnapshotRequest is loaded - into the environment. - - .. 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.orchestration.airflow import service_v1 - - async def sample_load_snapshot(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.LoadSnapshotRequest( - ) - - # Make the request - operation = client.load_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.LoadSnapshotRequest, dict]]): - The request object. Request to load a snapshot into a - Cloud Composer environment. - 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.orchestration.airflow.service_v1.types.LoadSnapshotResponse` - Response to LoadSnapshotRequest. - - """ - # 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, environments.LoadSnapshotRequest): - request = environments.LoadSnapshotRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.load_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.LoadSnapshotResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def database_failover(self, - request: Optional[Union[environments.DatabaseFailoverRequest, dict]] = 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"""Triggers database failover (only for highly resilient - environments). - - .. 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.orchestration.airflow import service_v1 - - async def sample_database_failover(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.DatabaseFailoverRequest( - ) - - # Make the request - operation = client.database_failover(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.DatabaseFailoverRequest, dict]]): - The request object. Request to trigger database failover - (only for highly resilient - environments). - 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.orchestration.airflow.service_v1.types.DatabaseFailoverResponse` - Response for DatabaseFailoverRequest. - - """ - # 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, environments.DatabaseFailoverRequest): - request = environments.DatabaseFailoverRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.database_failover] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.DatabaseFailoverResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def fetch_database_properties(self, - request: Optional[Union[environments.FetchDatabasePropertiesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.FetchDatabasePropertiesResponse: - r"""Fetches database properties. - - .. 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.orchestration.airflow import service_v1 - - async def sample_fetch_database_properties(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.FetchDatabasePropertiesRequest( - environment="environment_value", - ) - - # Make the request - response = await client.fetch_database_properties(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesRequest, dict]]): - The request object. Request to fetch properties of - environment's database. - 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.orchestration.airflow.service_v1.types.FetchDatabasePropertiesResponse: - Response for - FetchDatabasePropertiesRequest. - - """ - # 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, environments.FetchDatabasePropertiesRequest): - request = environments.FetchDatabasePropertiesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.fetch_database_properties] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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 __aenter__(self) -> "EnvironmentsAsyncClient": - 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__ = ( - "EnvironmentsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py deleted file mode 100644 index 9b20c3657db6..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py +++ /dev/null @@ -1,3589 +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 http import HTTPStatus -import json -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.orchestration.airflow.service_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.orchestration.airflow.service_v1.services.environments import pagers -from google.cloud.orchestration.airflow.service_v1.types import environments -from google.cloud.orchestration.airflow.service_v1.types import operations -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 EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EnvironmentsGrpcTransport -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .transports.rest import EnvironmentsRestTransport - - -class EnvironmentsClientMeta(type): - """Metaclass for the Environments 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[EnvironmentsTransport]] - _transport_registry["grpc"] = EnvironmentsGrpcTransport - _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport - _transport_registry["rest"] = EnvironmentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EnvironmentsTransport]: - """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 EnvironmentsClient(metaclass=EnvironmentsClientMeta): - """Managed Apache Airflow Environments.""" - - @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 = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "composer.{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: - EnvironmentsClient: 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: - EnvironmentsClient: 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) -> EnvironmentsTransport: - """Returns the transport used by the client instance. - - Returns: - EnvironmentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def environment_path(project: str,location: str,environment: str,) -> str: - """Returns a fully-qualified environment string.""" - return "projects/{project}/locations/{location}/environments/{environment}".format(project=project, location=location, environment=environment, ) - - @staticmethod - def parse_environment_path(path: str) -> Dict[str,str]: - """Parses a environment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def user_workloads_config_map_path(project: str,location: str,environment: str,user_workloads_config_map: str,) -> str: - """Returns a fully-qualified user_workloads_config_map string.""" - return "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsConfigMaps/{user_workloads_config_map}".format(project=project, location=location, environment=environment, user_workloads_config_map=user_workloads_config_map, ) - - @staticmethod - def parse_user_workloads_config_map_path(path: str) -> Dict[str,str]: - """Parses a user_workloads_config_map path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)/userWorkloadsConfigMaps/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def user_workloads_secret_path(project: str,location: str,environment: str,user_workloads_secret: str,) -> str: - """Returns a fully-qualified user_workloads_secret string.""" - return "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsSecrets/{user_workloads_secret}".format(project=project, location=location, environment=environment, user_workloads_secret=user_workloads_secret, ) - - @staticmethod - def parse_user_workloads_secret_path(path: str) -> Dict[str,str]: - """Parses a user_workloads_secret path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)/userWorkloadsSecrets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = EnvironmentsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = EnvironmentsClient._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 = EnvironmentsClient._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 - - def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError - ) -> None: - """Adds credential info string to error details for 401/403/404 errors. - - Args: - error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. - """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @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, EnvironmentsTransport, Callable[..., EnvironmentsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the environments 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,EnvironmentsTransport,Callable[..., EnvironmentsTransport]]]): - 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 EnvironmentsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = EnvironmentsClient._read_environment_variables() - self._client_cert_source = EnvironmentsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = EnvironmentsClient._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, EnvironmentsTransport) - if transport_provided: - # transport is a EnvironmentsTransport 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(EnvironmentsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - EnvironmentsClient._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[EnvironmentsTransport], Callable[..., EnvironmentsTransport]] = ( - EnvironmentsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., EnvironmentsTransport], 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.orchestration.airflow.service_v1.EnvironmentsClient`.", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "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.orchestration.airflow.service.v1.Environments", - "credentialsType": None, - } - ) - - def create_environment(self, - request: Optional[Union[environments.CreateEnvironmentRequest, dict]] = None, - *, - parent: Optional[str] = None, - environment: Optional[environments.Environment] = 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"""Create a new environment. - - .. 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.orchestration.airflow import service_v1 - - def sample_create_environment(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.CreateEnvironmentRequest( - ) - - # Make the request - operation = client.create_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.CreateEnvironmentRequest, dict]): - The request object. Create a new environment. - parent (str): - The parent must be of the form - "projects/{projectId}/locations/{locationId}". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (google.cloud.orchestration.airflow.service_v1.types.Environment): - The environment to create. - This corresponds to the ``environment`` 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.orchestration.airflow.service_v1.types.Environment` - An environment for running orchestration tasks. - - """ - # 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. - flattened_params = [parent, environment] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateEnvironmentRequest): - request = environments.CreateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if environment is not None: - request.environment = environment - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_environment] - - # 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, - environments.Environment, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_environment(self, - request: Optional[Union[environments.GetEnvironmentRequest, 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]]] = (), - ) -> environments.Environment: - r"""Get an existing environment. - - .. 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.orchestration.airflow import service_v1 - - def sample_get_environment(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.GetEnvironmentRequest( - ) - - # Make the request - response = client.get_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.GetEnvironmentRequest, dict]): - The request object. Get an environment. - name (str): - The resource name of the environment - to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1.types.Environment: - An environment for running - orchestration tasks. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetEnvironmentRequest): - request = environments.GetEnvironmentRequest(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_environment] - - # 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_environments(self, - request: Optional[Union[environments.ListEnvironmentsRequest, 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.ListEnvironmentsPager: - r"""List environments. - - .. 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.orchestration.airflow import service_v1 - - def sample_list_environments(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.ListEnvironmentsRequest( - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest, dict]): - The request object. List environments in a project and - location. - parent (str): - List environments in the given - project and location, in the form: - "projects/{projectId}/locations/{locationId}" - - 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.orchestration.airflow.service_v1.services.environments.pagers.ListEnvironmentsPager: - The environments in a project and - location. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListEnvironmentsRequest): - request = environments.ListEnvironmentsRequest(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_environments] - - # 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.ListEnvironmentsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_environment(self, - request: Optional[Union[environments.UpdateEnvironmentRequest, dict]] = None, - *, - name: Optional[str] = None, - environment: Optional[environments.Environment] = 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"""Update an environment. - - .. 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.orchestration.airflow import service_v1 - - def sample_update_environment(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.UpdateEnvironmentRequest( - ) - - # Make the request - operation = client.update_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.UpdateEnvironmentRequest, dict]): - The request object. Update an environment. - name (str): - The relative resource name of the - environment to update, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (google.cloud.orchestration.airflow.service_v1.types.Environment): - A patch environment. Fields specified by the - ``updateMask`` will be copied from the patch environment - into the environment under update. - - This corresponds to the ``environment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A comma-separated list of paths, relative to - ``Environment``, of fields to update. For example, to - set the version of scikit-learn to install in the - environment to 0.19.0 and to remove an existing - installation of numpy, the ``updateMask`` parameter - would include the following two ``paths`` values: - "config.softwareConfig.pypiPackages.scikit-learn" and - "config.softwareConfig.pypiPackages.numpy". The included - patch environment would specify the scikit-learn version - as follows: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "scikit-learn":"==0.19.0" - } - } - } - } - - Note that in the above example, any existing PyPI - packages other than scikit-learn and numpy will be - unaffected. - - Only one update type may be included in a single - request's ``updateMask``. For example, one cannot update - both the PyPI packages and labels in the same request. - However, it is possible to update multiple members of a - map field simultaneously in the same request. For - example, to set the labels "label1" and "label2" while - clearing "label3" (assuming it already exists), one can - provide the paths "labels.label1", "labels.label2", and - "labels.label3" and populate the patch environment as - follows: - - :: - - { - "labels":{ - "label1":"new-label1-value" - "label2":"new-label2-value" - } - } - - Note that in the above example, any existing labels that - are not included in the ``updateMask`` will be - unaffected. - - It is also possible to replace an entire map field by - providing the map field's path in the ``updateMask``. - The new value of the field will be that which is - provided in the patch environment. For example, to - delete all pre-existing user-specified PyPI packages and - install botocore at version 1.7.14, the ``updateMask`` - would contain the path - "config.softwareConfig.pypiPackages", and the patch - environment would be the following: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "botocore":"==1.7.14" - } - } - } - } - - **Note:** Only the following fields can be updated: - - - ``config.softwareConfig.pypiPackages`` - - - Replace all custom custom PyPI packages. If a - replacement package map is not included in - ``environment``, all custom PyPI packages are - cleared. It is an error to provide both this mask - and a mask specifying an individual package. - - - ``config.softwareConfig.pypiPackages.``\ packagename - - - Update the custom PyPI package *packagename*, - preserving other packages. To delete the package, - include it in ``updateMask``, and omit the mapping - for it in - ``environment.config.softwareConfig.pypiPackages``. - It is an error to provide both a mask of this form - and the ``config.softwareConfig.pypiPackages`` - mask. - - - ``labels`` - - - Replace all environment labels. If a replacement - labels map is not included in ``environment``, all - labels are cleared. It is an error to provide both - this mask and a mask specifying one or more - individual labels. - - - ``labels.``\ labelName - - - Set the label named *labelName*, while preserving - other labels. To delete the label, include it in - ``updateMask`` and omit its mapping in - ``environment.labels``. It is an error to provide - both a mask of this form and the ``labels`` mask. - - - ``config.nodeCount`` - - - Horizontally scale the number of nodes in the - environment. An integer greater than or equal to 3 - must be provided in the ``config.nodeCount`` - field. Supported for Cloud Composer environments - in versions composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerNetworkAccessControl`` - - - Replace the environment's current - ``WebServerNetworkAccessControl``. - - - ``config.softwareConfig.airflowConfigOverrides`` - - - Replace all Apache Airflow config overrides. If a - replacement config overrides map is not included - in ``environment``, all config overrides are - cleared. It is an error to provide both this mask - and a mask specifying one or more individual - config overrides. - - - ``config.softwareConfig.airflowConfigOverrides.``\ section-name - - - Override the Apache Airflow config property *name* - in the section named *section*, preserving other - properties. To delete the property override, - include it in ``updateMask`` and omit its mapping - in - ``environment.config.softwareConfig.airflowConfigOverrides``. - It is an error to provide both a mask of this form - and the - ``config.softwareConfig.airflowConfigOverrides`` - mask. - - - ``config.softwareConfig.envVariables`` - - - Replace all environment variables. If a - replacement environment variable map is not - included in ``environment``, all custom - environment variables are cleared. - - - ``config.softwareConfig.schedulerCount`` - - - Horizontally scale the number of schedulers in - Airflow. A positive integer not greater than the - number of nodes must be provided in the - ``config.softwareConfig.schedulerCount`` field. - Supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-2.*.*. - - - ``config.databaseConfig.machineType`` - - - Cloud SQL machine type used by Airflow database. - It has to be one of: db-n1-standard-2, - db-n1-standard-4, db-n1-standard-8 or - db-n1-standard-16. Supported for Cloud Composer - environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerConfig.machineType`` - - - Machine type on which Airflow web server is - running. It has to be one of: - composer-n1-webserver-2, composer-n1-webserver-4 - or composer-n1-webserver-8. Supported for Cloud - Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - 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.orchestration.airflow.service_v1.types.Environment` - An environment for running orchestration tasks. - - """ - # 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. - flattened_params = [name, environment, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateEnvironmentRequest): - request = environments.UpdateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if environment is not None: - request.environment = environment - 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_environment] - - # 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, - environments.Environment, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_environment(self, - request: Optional[Union[environments.DeleteEnvironmentRequest, 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"""Delete an environment. - - .. 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.orchestration.airflow import service_v1 - - def sample_delete_environment(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.DeleteEnvironmentRequest( - ) - - # Make the request - operation = client.delete_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.DeleteEnvironmentRequest, dict]): - The request object. Delete an environment. - name (str): - The environment to delete, in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteEnvironmentRequest): - request = environments.DeleteEnvironmentRequest(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_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def execute_airflow_command(self, - request: Optional[Union[environments.ExecuteAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.ExecuteAirflowCommandResponse: - r"""Executes Airflow CLI command. - - .. 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.orchestration.airflow import service_v1 - - def sample_execute_airflow_command(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.ExecuteAirflowCommandRequest( - ) - - # Make the request - response = client.execute_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandRequest, dict]): - The request object. Execute Airflow Command request. - retry (google.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.orchestration.airflow.service_v1.types.ExecuteAirflowCommandResponse: - Response to - ExecuteAirflowCommandRequest. - - """ - # 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, environments.ExecuteAirflowCommandRequest): - request = environments.ExecuteAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.execute_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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 stop_airflow_command(self, - request: Optional[Union[environments.StopAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.StopAirflowCommandResponse: - r"""Stops Airflow CLI command execution. - - .. 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.orchestration.airflow import service_v1 - - def sample_stop_airflow_command(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.StopAirflowCommandRequest( - ) - - # Make the request - response = client.stop_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandRequest, dict]): - The request object. Stop Airflow Command request. - retry (google.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.orchestration.airflow.service_v1.types.StopAirflowCommandResponse: - Response to - StopAirflowCommandRequest. - - """ - # 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, environments.StopAirflowCommandRequest): - request = environments.StopAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.stop_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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 poll_airflow_command(self, - request: Optional[Union[environments.PollAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.PollAirflowCommandResponse: - r"""Polls Airflow CLI command execution and fetches logs. - - .. 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.orchestration.airflow import service_v1 - - def sample_poll_airflow_command(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.PollAirflowCommandRequest( - ) - - # Make the request - response = client.poll_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandRequest, dict]): - The request object. Poll Airflow Command request. - retry (google.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.orchestration.airflow.service_v1.types.PollAirflowCommandResponse: - Response to - PollAirflowCommandRequest. - - """ - # 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, environments.PollAirflowCommandRequest): - request = environments.PollAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.poll_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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_workloads(self, - request: Optional[Union[environments.ListWorkloadsRequest, 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.ListWorkloadsPager: - r"""Lists workloads in a Cloud Composer environment. Workload is a - unit that runs a single Composer component. - - This method is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_list_workloads(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.ListWorkloadsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workloads(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest, dict]): - The request object. Request for listing workloads in a - Cloud Composer environment. - parent (str): - Required. The environment name to get - workloads for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1.services.environments.pagers.ListWorkloadsPager: - Response to ListWorkloadsRequest. - - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListWorkloadsRequest): - request = environments.ListWorkloadsRequest(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_workloads] - - # 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.ListWorkloadsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def check_upgrade(self, - request: Optional[Union[environments.CheckUpgradeRequest, dict]] = 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"""Check if an upgrade operation on the environment will - succeed. - In case of problems detailed info can be found in the - returned 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.orchestration.airflow import service_v1 - - def sample_check_upgrade(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.CheckUpgradeRequest( - environment="environment_value", - ) - - # Make the request - operation = client.check_upgrade(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.CheckUpgradeRequest, dict]): - The request object. Request to check whether image - upgrade will succeed. - retry (google.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.orchestration.airflow.service_v1.types.CheckUpgradeResponse` Message containing information about the result of an upgrade check - operation. - - """ - # 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, environments.CheckUpgradeRequest): - request = environments.CheckUpgradeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.check_upgrade] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.CheckUpgradeResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def create_user_workloads_secret(self, - request: Optional[Union[environments.CreateUserWorkloadsSecretRequest, dict]] = None, - *, - parent: Optional[str] = None, - user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_create_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.CreateUserWorkloadsSecretRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsSecretRequest, dict]): - The request object. Create user workloads Secret request. - parent (str): - Required. The environment name to - create a Secret for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_workloads_secret (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret): - Required. User workloads Secret to - create. - - This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [parent, user_workloads_secret] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateUserWorkloadsSecretRequest): - request = environments.CreateUserWorkloadsSecretRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_workloads_secret is not None: - request.user_workloads_secret = user_workloads_secret - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_user_workloads_secret] - - # 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 get_user_workloads_secret(self, - request: Optional[Union[environments.GetUserWorkloadsSecretRequest, 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]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Gets an existing user workloads Secret. Values of the "data" - field in the response are cleared. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_get_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.GetUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - response = client.get_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsSecretRequest, dict]): - The request object. Get user workloads Secret request. - name (str): - Required. The resource name of the - Secret to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" - - 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetUserWorkloadsSecretRequest): - request = environments.GetUserWorkloadsSecretRequest(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_user_workloads_secret] - - # 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_user_workloads_secrets(self, - request: Optional[Union[environments.ListUserWorkloadsSecretsRequest, 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.ListUserWorkloadsSecretsPager: - r"""Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_list_user_workloads_secrets(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.ListUserWorkloadsSecretsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_secrets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest, dict]): - The request object. List user workloads Secrets request. - parent (str): - Required. List Secrets in the given - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsSecretsPager: - The user workloads Secrets for a - given environment. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListUserWorkloadsSecretsRequest): - request = environments.ListUserWorkloadsSecretsRequest(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_user_workloads_secrets] - - # 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.ListUserWorkloadsSecretsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_user_workloads_secret(self, - request: Optional[Union[environments.UpdateUserWorkloadsSecretRequest, dict]] = None, - *, - user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_update_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.UpdateUserWorkloadsSecretRequest( - ) - - # Make the request - response = client.update_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsSecretRequest, dict]): - The request object. Update user workloads Secret request. - user_workloads_secret (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret): - Optional. User workloads Secret to - override. - - This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [user_workloads_secret] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateUserWorkloadsSecretRequest): - request = environments.UpdateUserWorkloadsSecretRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if user_workloads_secret is not None: - request.user_workloads_secret = user_workloads_secret - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_user_workloads_secret] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user_workloads_secret.name", request.user_workloads_secret.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_user_workloads_secret(self, - request: Optional[Union[environments.DeleteUserWorkloadsSecretRequest, 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]]] = (), - ) -> None: - r"""Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_delete_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.DeleteUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - client.delete_user_workloads_secret(request=request) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsSecretRequest, dict]): - The request object. Delete user workloads Secret request. - name (str): - Required. The Secret to delete, in - the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" - - 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`. - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteUserWorkloadsSecretRequest): - request = environments.DeleteUserWorkloadsSecretRequest(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_user_workloads_secret] - - # 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 create_user_workloads_config_map(self, - request: Optional[Union[environments.CreateUserWorkloadsConfigMapRequest, dict]] = None, - *, - parent: Optional[str] = None, - user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_create_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.CreateUserWorkloadsConfigMapRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsConfigMapRequest, dict]): - The request object. Create user workloads ConfigMap - request. - parent (str): - Required. The environment name to - create a ConfigMap for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_workloads_config_map (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap): - Required. User workloads ConfigMap to - create. - - This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [parent, user_workloads_config_map] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateUserWorkloadsConfigMapRequest): - request = environments.CreateUserWorkloadsConfigMapRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_workloads_config_map is not None: - request.user_workloads_config_map = user_workloads_config_map - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_user_workloads_config_map] - - # 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 get_user_workloads_config_map(self, - request: Optional[Union[environments.GetUserWorkloadsConfigMapRequest, 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]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_get_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.GetUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - response = client.get_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsConfigMapRequest, dict]): - The request object. Get user workloads ConfigMap request. - name (str): - Required. The resource name of the - ConfigMap to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" - - 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetUserWorkloadsConfigMapRequest): - request = environments.GetUserWorkloadsConfigMapRequest(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_user_workloads_config_map] - - # 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_user_workloads_config_maps(self, - request: Optional[Union[environments.ListUserWorkloadsConfigMapsRequest, 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.ListUserWorkloadsConfigMapsPager: - r"""Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_list_user_workloads_config_maps(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.ListUserWorkloadsConfigMapsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_config_maps(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest, dict]): - The request object. List user workloads ConfigMaps - request. - parent (str): - Required. List ConfigMaps in the - given environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsConfigMapsPager: - The user workloads ConfigMaps for a - given environment. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListUserWorkloadsConfigMapsRequest): - request = environments.ListUserWorkloadsConfigMapsRequest(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_user_workloads_config_maps] - - # 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.ListUserWorkloadsConfigMapsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_user_workloads_config_map(self, - request: Optional[Union[environments.UpdateUserWorkloadsConfigMapRequest, dict]] = None, - *, - user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_update_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.UpdateUserWorkloadsConfigMapRequest( - ) - - # Make the request - response = client.update_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsConfigMapRequest, dict]): - The request object. Update user workloads ConfigMap - request. - user_workloads_config_map (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap): - Optional. User workloads ConfigMap to - override. - - This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [user_workloads_config_map] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateUserWorkloadsConfigMapRequest): - request = environments.UpdateUserWorkloadsConfigMapRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if user_workloads_config_map is not None: - request.user_workloads_config_map = user_workloads_config_map - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_user_workloads_config_map] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user_workloads_config_map.name", request.user_workloads_config_map.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_user_workloads_config_map(self, - request: Optional[Union[environments.DeleteUserWorkloadsConfigMapRequest, 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]]] = (), - ) -> None: - r"""Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1 - - def sample_delete_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.DeleteUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - client.delete_user_workloads_config_map(request=request) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsConfigMapRequest, dict]): - The request object. Delete user workloads ConfigMap - request. - name (str): - Required. The ConfigMap to delete, in - the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" - - 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`. - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteUserWorkloadsConfigMapRequest): - request = environments.DeleteUserWorkloadsConfigMapRequest(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_user_workloads_config_map] - - # 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 save_snapshot(self, - request: Optional[Union[environments.SaveSnapshotRequest, dict]] = 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 snapshots of a Cloud Composer environment. - - As a result of this operation, snapshot of environment's - state is stored in a location specified in the - SaveSnapshotRequest. - - .. 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.orchestration.airflow import service_v1 - - def sample_save_snapshot(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.SaveSnapshotRequest( - ) - - # Make the request - operation = client.save_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.SaveSnapshotRequest, dict]): - The request object. Request to create a snapshot of a - Cloud Composer environment. - retry (google.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.orchestration.airflow.service_v1.types.SaveSnapshotResponse` - Response to SaveSnapshotRequest. - - """ - # 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, environments.SaveSnapshotRequest): - request = environments.SaveSnapshotRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.save_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.SaveSnapshotResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def load_snapshot(self, - request: Optional[Union[environments.LoadSnapshotRequest, dict]] = 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"""Loads a snapshot of a Cloud Composer environment. - - As a result of this operation, a snapshot of - environment's specified in LoadSnapshotRequest is loaded - into the environment. - - .. 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.orchestration.airflow import service_v1 - - def sample_load_snapshot(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.LoadSnapshotRequest( - ) - - # Make the request - operation = client.load_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.LoadSnapshotRequest, dict]): - The request object. Request to load a snapshot into a - Cloud Composer environment. - retry (google.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.orchestration.airflow.service_v1.types.LoadSnapshotResponse` - Response to LoadSnapshotRequest. - - """ - # 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, environments.LoadSnapshotRequest): - request = environments.LoadSnapshotRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.load_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.LoadSnapshotResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def database_failover(self, - request: Optional[Union[environments.DatabaseFailoverRequest, dict]] = 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"""Triggers database failover (only for highly resilient - environments). - - .. 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.orchestration.airflow import service_v1 - - def sample_database_failover(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.DatabaseFailoverRequest( - ) - - # Make the request - operation = client.database_failover(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.DatabaseFailoverRequest, dict]): - The request object. Request to trigger database failover - (only for highly resilient - environments). - retry (google.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.orchestration.airflow.service_v1.types.DatabaseFailoverResponse` - Response for DatabaseFailoverRequest. - - """ - # 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, environments.DatabaseFailoverRequest): - request = environments.DatabaseFailoverRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.database_failover] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.DatabaseFailoverResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def fetch_database_properties(self, - request: Optional[Union[environments.FetchDatabasePropertiesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.FetchDatabasePropertiesResponse: - r"""Fetches database properties. - - .. 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.orchestration.airflow import service_v1 - - def sample_fetch_database_properties(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.FetchDatabasePropertiesRequest( - environment="environment_value", - ) - - # Make the request - response = client.fetch_database_properties(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesRequest, dict]): - The request object. Request to fetch properties of - environment's database. - retry (google.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.orchestration.airflow.service_v1.types.FetchDatabasePropertiesResponse: - Response for - FetchDatabasePropertiesRequest. - - """ - # 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, environments.FetchDatabasePropertiesRequest): - request = environments.FetchDatabasePropertiesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.fetch_database_properties] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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) -> "EnvironmentsClient": - 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() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - 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() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - 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,) - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EnvironmentsClient", -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py deleted file mode 100644 index 0163c1f1931e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py +++ /dev/null @@ -1,583 +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.orchestration.airflow.service_v1.types import environments - - -class ListEnvironmentsPager: - """A pager for iterating through ``list_environments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEnvironments`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse` - 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[..., environments.ListEnvironmentsResponse], - request: environments.ListEnvironmentsRequest, - response: environments.ListEnvironmentsResponse, - *, - 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.orchestration.airflow.service_v1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse): - 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 = environments.ListEnvironmentsRequest(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[environments.ListEnvironmentsResponse]: - 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[environments.Environment]: - for page in self.pages: - yield from page.environments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEnvironmentsAsyncPager: - """A pager for iterating through ``list_environments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEnvironments`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse` - 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[environments.ListEnvironmentsResponse]], - request: environments.ListEnvironmentsRequest, - response: environments.ListEnvironmentsResponse, - *, - 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.orchestration.airflow.service_v1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse): - 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 = environments.ListEnvironmentsRequest(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[environments.ListEnvironmentsResponse]: - 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[environments.Environment]: - async def async_generator(): - async for page in self.pages: - for response in page.environments: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkloadsPager: - """A pager for iterating through ``list_workloads`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workloads`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkloads`` requests and continue to iterate - through the ``workloads`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse` - 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[..., environments.ListWorkloadsResponse], - request: environments.ListWorkloadsRequest, - response: environments.ListWorkloadsResponse, - *, - 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.orchestration.airflow.service_v1.types.ListWorkloadsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse): - 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 = environments.ListWorkloadsRequest(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[environments.ListWorkloadsResponse]: - 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[environments.ListWorkloadsResponse.ComposerWorkload]: - for page in self.pages: - yield from page.workloads - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkloadsAsyncPager: - """A pager for iterating through ``list_workloads`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workloads`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkloads`` requests and continue to iterate - through the ``workloads`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse` - 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[environments.ListWorkloadsResponse]], - request: environments.ListWorkloadsRequest, - response: environments.ListWorkloadsResponse, - *, - 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.orchestration.airflow.service_v1.types.ListWorkloadsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse): - 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 = environments.ListWorkloadsRequest(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[environments.ListWorkloadsResponse]: - 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[environments.ListWorkloadsResponse.ComposerWorkload]: - async def async_generator(): - async for page in self.pages: - for response in page.workloads: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUserWorkloadsSecretsPager: - """A pager for iterating through ``list_user_workloads_secrets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``user_workloads_secrets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUserWorkloadsSecrets`` requests and continue to iterate - through the ``user_workloads_secrets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse` - 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[..., environments.ListUserWorkloadsSecretsResponse], - request: environments.ListUserWorkloadsSecretsRequest, - response: environments.ListUserWorkloadsSecretsResponse, - *, - 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.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse): - 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 = environments.ListUserWorkloadsSecretsRequest(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[environments.ListUserWorkloadsSecretsResponse]: - 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[environments.UserWorkloadsSecret]: - for page in self.pages: - yield from page.user_workloads_secrets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUserWorkloadsSecretsAsyncPager: - """A pager for iterating through ``list_user_workloads_secrets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``user_workloads_secrets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUserWorkloadsSecrets`` requests and continue to iterate - through the ``user_workloads_secrets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse` - 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[environments.ListUserWorkloadsSecretsResponse]], - request: environments.ListUserWorkloadsSecretsRequest, - response: environments.ListUserWorkloadsSecretsResponse, - *, - 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.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse): - 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 = environments.ListUserWorkloadsSecretsRequest(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[environments.ListUserWorkloadsSecretsResponse]: - 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[environments.UserWorkloadsSecret]: - async def async_generator(): - async for page in self.pages: - for response in page.user_workloads_secrets: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUserWorkloadsConfigMapsPager: - """A pager for iterating through ``list_user_workloads_config_maps`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``user_workloads_config_maps`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUserWorkloadsConfigMaps`` requests and continue to iterate - through the ``user_workloads_config_maps`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse` - 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[..., environments.ListUserWorkloadsConfigMapsResponse], - request: environments.ListUserWorkloadsConfigMapsRequest, - response: environments.ListUserWorkloadsConfigMapsResponse, - *, - 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.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse): - 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 = environments.ListUserWorkloadsConfigMapsRequest(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[environments.ListUserWorkloadsConfigMapsResponse]: - 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[environments.UserWorkloadsConfigMap]: - for page in self.pages: - yield from page.user_workloads_config_maps - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUserWorkloadsConfigMapsAsyncPager: - """A pager for iterating through ``list_user_workloads_config_maps`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``user_workloads_config_maps`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUserWorkloadsConfigMaps`` requests and continue to iterate - through the ``user_workloads_config_maps`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse` - 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[environments.ListUserWorkloadsConfigMapsResponse]], - request: environments.ListUserWorkloadsConfigMapsRequest, - response: environments.ListUserWorkloadsConfigMapsResponse, - *, - 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.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse): - 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 = environments.ListUserWorkloadsConfigMapsRequest(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[environments.ListUserWorkloadsConfigMapsResponse]: - 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[environments.UserWorkloadsConfigMap]: - async def async_generator(): - async for page in self.pages: - for response in page.user_workloads_config_maps: - 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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/README.rst deleted file mode 100644 index bce85d4987a6..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`EnvironmentsTransport` is the ABC for all transports. -- public child `EnvironmentsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `EnvironmentsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseEnvironmentsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `EnvironmentsRestTransport` 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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/__init__.py deleted file mode 100644 index 0fb4434d4920..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/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 EnvironmentsTransport -from .grpc import EnvironmentsGrpcTransport -from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .rest import EnvironmentsRestTransport -from .rest import EnvironmentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] -_transport_registry['grpc'] = EnvironmentsGrpcTransport -_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport -_transport_registry['rest'] = EnvironmentsRestTransport - -__all__ = ( - 'EnvironmentsTransport', - 'EnvironmentsGrpcTransport', - 'EnvironmentsGrpcAsyncIOTransport', - 'EnvironmentsRestTransport', - 'EnvironmentsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py deleted file mode 100644 index d0bdd6c78241..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py +++ /dev/null @@ -1,526 +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.orchestration.airflow.service_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.orchestration.airflow.service_v1.types import environments -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class EnvironmentsTransport(abc.ABC): - """Abstract transport class for Environments.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'composer.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: 'composer.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_environment: gapic_v1.method.wrap_method( - self.create_environment, - default_timeout=None, - client_info=client_info, - ), - self.get_environment: gapic_v1.method.wrap_method( - self.get_environment, - default_timeout=None, - client_info=client_info, - ), - self.list_environments: gapic_v1.method.wrap_method( - self.list_environments, - default_timeout=None, - client_info=client_info, - ), - self.update_environment: gapic_v1.method.wrap_method( - self.update_environment, - default_timeout=None, - client_info=client_info, - ), - self.delete_environment: gapic_v1.method.wrap_method( - self.delete_environment, - default_timeout=None, - client_info=client_info, - ), - self.execute_airflow_command: gapic_v1.method.wrap_method( - self.execute_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.stop_airflow_command: gapic_v1.method.wrap_method( - self.stop_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.poll_airflow_command: gapic_v1.method.wrap_method( - self.poll_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.list_workloads: gapic_v1.method.wrap_method( - self.list_workloads, - default_timeout=None, - client_info=client_info, - ), - self.check_upgrade: gapic_v1.method.wrap_method( - self.check_upgrade, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_secret: gapic_v1.method.wrap_method( - self.create_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_secret: gapic_v1.method.wrap_method( - self.get_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_secrets: gapic_v1.method.wrap_method( - self.list_user_workloads_secrets, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_secret: gapic_v1.method.wrap_method( - self.update_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_secret: gapic_v1.method.wrap_method( - self.delete_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_config_map: gapic_v1.method.wrap_method( - self.create_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_config_map: gapic_v1.method.wrap_method( - self.get_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_config_maps: gapic_v1.method.wrap_method( - self.list_user_workloads_config_maps, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_config_map: gapic_v1.method.wrap_method( - self.update_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_config_map: gapic_v1.method.wrap_method( - self.delete_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.save_snapshot: gapic_v1.method.wrap_method( - self.save_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.load_snapshot: gapic_v1.method.wrap_method( - self.load_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.database_failover: gapic_v1.method.wrap_method( - self.database_failover, - default_timeout=None, - client_info=client_info, - ), - self.fetch_database_properties: gapic_v1.method.wrap_method( - self.fetch_database_properties, - 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_environment(self) -> Callable[ - [environments.CreateEnvironmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_environment(self) -> Callable[ - [environments.GetEnvironmentRequest], - Union[ - environments.Environment, - Awaitable[environments.Environment] - ]]: - raise NotImplementedError() - - @property - def list_environments(self) -> Callable[ - [environments.ListEnvironmentsRequest], - Union[ - environments.ListEnvironmentsResponse, - Awaitable[environments.ListEnvironmentsResponse] - ]]: - raise NotImplementedError() - - @property - def update_environment(self) -> Callable[ - [environments.UpdateEnvironmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_environment(self) -> Callable[ - [environments.DeleteEnvironmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def execute_airflow_command(self) -> Callable[ - [environments.ExecuteAirflowCommandRequest], - Union[ - environments.ExecuteAirflowCommandResponse, - Awaitable[environments.ExecuteAirflowCommandResponse] - ]]: - raise NotImplementedError() - - @property - def stop_airflow_command(self) -> Callable[ - [environments.StopAirflowCommandRequest], - Union[ - environments.StopAirflowCommandResponse, - Awaitable[environments.StopAirflowCommandResponse] - ]]: - raise NotImplementedError() - - @property - def poll_airflow_command(self) -> Callable[ - [environments.PollAirflowCommandRequest], - Union[ - environments.PollAirflowCommandResponse, - Awaitable[environments.PollAirflowCommandResponse] - ]]: - raise NotImplementedError() - - @property - def list_workloads(self) -> Callable[ - [environments.ListWorkloadsRequest], - Union[ - environments.ListWorkloadsResponse, - Awaitable[environments.ListWorkloadsResponse] - ]]: - raise NotImplementedError() - - @property - def check_upgrade(self) -> Callable[ - [environments.CheckUpgradeRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def create_user_workloads_secret(self) -> Callable[ - [environments.CreateUserWorkloadsSecretRequest], - Union[ - environments.UserWorkloadsSecret, - Awaitable[environments.UserWorkloadsSecret] - ]]: - raise NotImplementedError() - - @property - def get_user_workloads_secret(self) -> Callable[ - [environments.GetUserWorkloadsSecretRequest], - Union[ - environments.UserWorkloadsSecret, - Awaitable[environments.UserWorkloadsSecret] - ]]: - raise NotImplementedError() - - @property - def list_user_workloads_secrets(self) -> Callable[ - [environments.ListUserWorkloadsSecretsRequest], - Union[ - environments.ListUserWorkloadsSecretsResponse, - Awaitable[environments.ListUserWorkloadsSecretsResponse] - ]]: - raise NotImplementedError() - - @property - def update_user_workloads_secret(self) -> Callable[ - [environments.UpdateUserWorkloadsSecretRequest], - Union[ - environments.UserWorkloadsSecret, - Awaitable[environments.UserWorkloadsSecret] - ]]: - raise NotImplementedError() - - @property - def delete_user_workloads_secret(self) -> Callable[ - [environments.DeleteUserWorkloadsSecretRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_user_workloads_config_map(self) -> Callable[ - [environments.CreateUserWorkloadsConfigMapRequest], - Union[ - environments.UserWorkloadsConfigMap, - Awaitable[environments.UserWorkloadsConfigMap] - ]]: - raise NotImplementedError() - - @property - def get_user_workloads_config_map(self) -> Callable[ - [environments.GetUserWorkloadsConfigMapRequest], - Union[ - environments.UserWorkloadsConfigMap, - Awaitable[environments.UserWorkloadsConfigMap] - ]]: - raise NotImplementedError() - - @property - def list_user_workloads_config_maps(self) -> Callable[ - [environments.ListUserWorkloadsConfigMapsRequest], - Union[ - environments.ListUserWorkloadsConfigMapsResponse, - Awaitable[environments.ListUserWorkloadsConfigMapsResponse] - ]]: - raise NotImplementedError() - - @property - def update_user_workloads_config_map(self) -> Callable[ - [environments.UpdateUserWorkloadsConfigMapRequest], - Union[ - environments.UserWorkloadsConfigMap, - Awaitable[environments.UserWorkloadsConfigMap] - ]]: - raise NotImplementedError() - - @property - def delete_user_workloads_config_map(self) -> Callable[ - [environments.DeleteUserWorkloadsConfigMapRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def save_snapshot(self) -> Callable[ - [environments.SaveSnapshotRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def load_snapshot(self) -> Callable[ - [environments.LoadSnapshotRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def database_failover(self) -> Callable[ - [environments.DatabaseFailoverRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def fetch_database_properties(self) -> Callable[ - [environments.FetchDatabasePropertiesRequest], - Union[ - environments.FetchDatabasePropertiesResponse, - Awaitable[environments.FetchDatabasePropertiesResponse] - ]]: - 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 delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'EnvironmentsTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py deleted file mode 100644 index 59bf8374726a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py +++ /dev/null @@ -1,1070 +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.orchestration.airflow.service_v1.types import environments -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import EnvironmentsTransport, 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.orchestration.airflow.service.v1.Environments", - "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.orchestration.airflow.service.v1.Environments", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class EnvironmentsGrpcTransport(EnvironmentsTransport): - """gRPC backend transport for Environments. - - Managed Apache Airflow Environments. - - 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 = 'composer.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: 'composer.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 = 'composer.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_environment(self) -> Callable[ - [environments.CreateEnvironmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the create environment method over gRPC. - - Create a new environment. - - Returns: - Callable[[~.CreateEnvironmentRequest], - ~.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_environment' not in self._stubs: - self._stubs['create_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/CreateEnvironment', - request_serializer=environments.CreateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_environment'] - - @property - def get_environment(self) -> Callable[ - [environments.GetEnvironmentRequest], - environments.Environment]: - r"""Return a callable for the get environment method over gRPC. - - Get an existing environment. - - Returns: - Callable[[~.GetEnvironmentRequest], - ~.Environment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_environment' not in self._stubs: - self._stubs['get_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/GetEnvironment', - request_serializer=environments.GetEnvironmentRequest.serialize, - response_deserializer=environments.Environment.deserialize, - ) - return self._stubs['get_environment'] - - @property - def list_environments(self) -> Callable[ - [environments.ListEnvironmentsRequest], - environments.ListEnvironmentsResponse]: - r"""Return a callable for the list environments method over gRPC. - - List environments. - - Returns: - Callable[[~.ListEnvironmentsRequest], - ~.ListEnvironmentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_environments' not in self._stubs: - self._stubs['list_environments'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/ListEnvironments', - request_serializer=environments.ListEnvironmentsRequest.serialize, - response_deserializer=environments.ListEnvironmentsResponse.deserialize, - ) - return self._stubs['list_environments'] - - @property - def update_environment(self) -> Callable[ - [environments.UpdateEnvironmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the update environment method over gRPC. - - Update an environment. - - Returns: - Callable[[~.UpdateEnvironmentRequest], - ~.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_environment' not in self._stubs: - self._stubs['update_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateEnvironment', - request_serializer=environments.UpdateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_environment'] - - @property - def delete_environment(self) -> Callable[ - [environments.DeleteEnvironmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete environment method over gRPC. - - Delete an environment. - - Returns: - Callable[[~.DeleteEnvironmentRequest], - ~.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_environment' not in self._stubs: - self._stubs['delete_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteEnvironment', - request_serializer=environments.DeleteEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_environment'] - - @property - def execute_airflow_command(self) -> Callable[ - [environments.ExecuteAirflowCommandRequest], - environments.ExecuteAirflowCommandResponse]: - r"""Return a callable for the execute airflow command method over gRPC. - - Executes Airflow CLI command. - - Returns: - Callable[[~.ExecuteAirflowCommandRequest], - ~.ExecuteAirflowCommandResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'execute_airflow_command' not in self._stubs: - self._stubs['execute_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/ExecuteAirflowCommand', - request_serializer=environments.ExecuteAirflowCommandRequest.serialize, - response_deserializer=environments.ExecuteAirflowCommandResponse.deserialize, - ) - return self._stubs['execute_airflow_command'] - - @property - def stop_airflow_command(self) -> Callable[ - [environments.StopAirflowCommandRequest], - environments.StopAirflowCommandResponse]: - r"""Return a callable for the stop airflow command method over gRPC. - - Stops Airflow CLI command execution. - - Returns: - Callable[[~.StopAirflowCommandRequest], - ~.StopAirflowCommandResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_airflow_command' not in self._stubs: - self._stubs['stop_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/StopAirflowCommand', - request_serializer=environments.StopAirflowCommandRequest.serialize, - response_deserializer=environments.StopAirflowCommandResponse.deserialize, - ) - return self._stubs['stop_airflow_command'] - - @property - def poll_airflow_command(self) -> Callable[ - [environments.PollAirflowCommandRequest], - environments.PollAirflowCommandResponse]: - r"""Return a callable for the poll airflow command method over gRPC. - - Polls Airflow CLI command execution and fetches logs. - - Returns: - Callable[[~.PollAirflowCommandRequest], - ~.PollAirflowCommandResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'poll_airflow_command' not in self._stubs: - self._stubs['poll_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/PollAirflowCommand', - request_serializer=environments.PollAirflowCommandRequest.serialize, - response_deserializer=environments.PollAirflowCommandResponse.deserialize, - ) - return self._stubs['poll_airflow_command'] - - @property - def list_workloads(self) -> Callable[ - [environments.ListWorkloadsRequest], - environments.ListWorkloadsResponse]: - r"""Return a callable for the list workloads method over gRPC. - - Lists workloads in a Cloud Composer environment. Workload is a - unit that runs a single Composer component. - - This method is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - - Returns: - Callable[[~.ListWorkloadsRequest], - ~.ListWorkloadsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workloads' not in self._stubs: - self._stubs['list_workloads'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/ListWorkloads', - request_serializer=environments.ListWorkloadsRequest.serialize, - response_deserializer=environments.ListWorkloadsResponse.deserialize, - ) - return self._stubs['list_workloads'] - - @property - def check_upgrade(self) -> Callable[ - [environments.CheckUpgradeRequest], - operations_pb2.Operation]: - r"""Return a callable for the check upgrade method over gRPC. - - Check if an upgrade operation on the environment will - succeed. - In case of problems detailed info can be found in the - returned Operation. - - Returns: - Callable[[~.CheckUpgradeRequest], - ~.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 'check_upgrade' not in self._stubs: - self._stubs['check_upgrade'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/CheckUpgrade', - request_serializer=environments.CheckUpgradeRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['check_upgrade'] - - @property - def create_user_workloads_secret(self) -> Callable[ - [environments.CreateUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - r"""Return a callable for the create user workloads secret method over gRPC. - - Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.CreateUserWorkloadsSecretRequest], - ~.UserWorkloadsSecret]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['create_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/CreateUserWorkloadsSecret', - request_serializer=environments.CreateUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['create_user_workloads_secret'] - - @property - def get_user_workloads_secret(self) -> Callable[ - [environments.GetUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - r"""Return a callable for the get user workloads secret method over gRPC. - - Gets an existing user workloads Secret. Values of the "data" - field in the response are cleared. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.GetUserWorkloadsSecretRequest], - ~.UserWorkloadsSecret]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['get_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/GetUserWorkloadsSecret', - request_serializer=environments.GetUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['get_user_workloads_secret'] - - @property - def list_user_workloads_secrets(self) -> Callable[ - [environments.ListUserWorkloadsSecretsRequest], - environments.ListUserWorkloadsSecretsResponse]: - r"""Return a callable for the list user workloads secrets method over gRPC. - - Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.ListUserWorkloadsSecretsRequest], - ~.ListUserWorkloadsSecretsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secrets' not in self._stubs: - self._stubs['list_user_workloads_secrets'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/ListUserWorkloadsSecrets', - request_serializer=environments.ListUserWorkloadsSecretsRequest.serialize, - response_deserializer=environments.ListUserWorkloadsSecretsResponse.deserialize, - ) - return self._stubs['list_user_workloads_secrets'] - - @property - def update_user_workloads_secret(self) -> Callable[ - [environments.UpdateUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - r"""Return a callable for the update user workloads secret method over gRPC. - - Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.UpdateUserWorkloadsSecretRequest], - ~.UserWorkloadsSecret]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['update_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateUserWorkloadsSecret', - request_serializer=environments.UpdateUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['update_user_workloads_secret'] - - @property - def delete_user_workloads_secret(self) -> Callable[ - [environments.DeleteUserWorkloadsSecretRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete user workloads secret method over gRPC. - - Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.DeleteUserWorkloadsSecretRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['delete_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteUserWorkloadsSecret', - request_serializer=environments.DeleteUserWorkloadsSecretRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user_workloads_secret'] - - @property - def create_user_workloads_config_map(self) -> Callable[ - [environments.CreateUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - r"""Return a callable for the create user workloads config - map method over gRPC. - - Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.CreateUserWorkloadsConfigMapRequest], - ~.UserWorkloadsConfigMap]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['create_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/CreateUserWorkloadsConfigMap', - request_serializer=environments.CreateUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['create_user_workloads_config_map'] - - @property - def get_user_workloads_config_map(self) -> Callable[ - [environments.GetUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - r"""Return a callable for the get user workloads config map method over gRPC. - - Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.GetUserWorkloadsConfigMapRequest], - ~.UserWorkloadsConfigMap]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['get_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/GetUserWorkloadsConfigMap', - request_serializer=environments.GetUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['get_user_workloads_config_map'] - - @property - def list_user_workloads_config_maps(self) -> Callable[ - [environments.ListUserWorkloadsConfigMapsRequest], - environments.ListUserWorkloadsConfigMapsResponse]: - r"""Return a callable for the list user workloads config - maps method over gRPC. - - Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.ListUserWorkloadsConfigMapsRequest], - ~.ListUserWorkloadsConfigMapsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_maps' not in self._stubs: - self._stubs['list_user_workloads_config_maps'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/ListUserWorkloadsConfigMaps', - request_serializer=environments.ListUserWorkloadsConfigMapsRequest.serialize, - response_deserializer=environments.ListUserWorkloadsConfigMapsResponse.deserialize, - ) - return self._stubs['list_user_workloads_config_maps'] - - @property - def update_user_workloads_config_map(self) -> Callable[ - [environments.UpdateUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - r"""Return a callable for the update user workloads config - map method over gRPC. - - Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.UpdateUserWorkloadsConfigMapRequest], - ~.UserWorkloadsConfigMap]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['update_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateUserWorkloadsConfigMap', - request_serializer=environments.UpdateUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['update_user_workloads_config_map'] - - @property - def delete_user_workloads_config_map(self) -> Callable[ - [environments.DeleteUserWorkloadsConfigMapRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete user workloads config - map method over gRPC. - - Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.DeleteUserWorkloadsConfigMapRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['delete_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteUserWorkloadsConfigMap', - request_serializer=environments.DeleteUserWorkloadsConfigMapRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user_workloads_config_map'] - - @property - def save_snapshot(self) -> Callable[ - [environments.SaveSnapshotRequest], - operations_pb2.Operation]: - r"""Return a callable for the save snapshot method over gRPC. - - Creates a snapshots of a Cloud Composer environment. - - As a result of this operation, snapshot of environment's - state is stored in a location specified in the - SaveSnapshotRequest. - - Returns: - Callable[[~.SaveSnapshotRequest], - ~.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 'save_snapshot' not in self._stubs: - self._stubs['save_snapshot'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/SaveSnapshot', - request_serializer=environments.SaveSnapshotRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['save_snapshot'] - - @property - def load_snapshot(self) -> Callable[ - [environments.LoadSnapshotRequest], - operations_pb2.Operation]: - r"""Return a callable for the load snapshot method over gRPC. - - Loads a snapshot of a Cloud Composer environment. - - As a result of this operation, a snapshot of - environment's specified in LoadSnapshotRequest is loaded - into the environment. - - Returns: - Callable[[~.LoadSnapshotRequest], - ~.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 'load_snapshot' not in self._stubs: - self._stubs['load_snapshot'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/LoadSnapshot', - request_serializer=environments.LoadSnapshotRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['load_snapshot'] - - @property - def database_failover(self) -> Callable[ - [environments.DatabaseFailoverRequest], - operations_pb2.Operation]: - r"""Return a callable for the database failover method over gRPC. - - Triggers database failover (only for highly resilient - environments). - - Returns: - Callable[[~.DatabaseFailoverRequest], - ~.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 'database_failover' not in self._stubs: - self._stubs['database_failover'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/DatabaseFailover', - request_serializer=environments.DatabaseFailoverRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['database_failover'] - - @property - def fetch_database_properties(self) -> Callable[ - [environments.FetchDatabasePropertiesRequest], - environments.FetchDatabasePropertiesResponse]: - r"""Return a callable for the fetch database properties method over gRPC. - - Fetches database properties. - - Returns: - Callable[[~.FetchDatabasePropertiesRequest], - ~.FetchDatabasePropertiesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fetch_database_properties' not in self._stubs: - self._stubs['fetch_database_properties'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/FetchDatabaseProperties', - request_serializer=environments.FetchDatabasePropertiesRequest.serialize, - response_deserializer=environments.FetchDatabasePropertiesResponse.deserialize, - ) - return self._stubs['fetch_database_properties'] - - 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 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__ = ( - 'EnvironmentsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py deleted file mode 100644 index 78698a3ca9b8..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py +++ /dev/null @@ -1,1220 +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.orchestration.airflow.service_v1.types import environments -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .grpc import EnvironmentsGrpcTransport - -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.orchestration.airflow.service.v1.Environments", - "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.orchestration.airflow.service.v1.Environments", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): - """gRPC AsyncIO backend transport for Environments. - - Managed Apache Airflow Environments. - - 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 = 'composer.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 = 'composer.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: 'composer.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_environment(self) -> Callable[ - [environments.CreateEnvironmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create environment method over gRPC. - - Create a new environment. - - Returns: - Callable[[~.CreateEnvironmentRequest], - 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_environment' not in self._stubs: - self._stubs['create_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/CreateEnvironment', - request_serializer=environments.CreateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_environment'] - - @property - def get_environment(self) -> Callable[ - [environments.GetEnvironmentRequest], - Awaitable[environments.Environment]]: - r"""Return a callable for the get environment method over gRPC. - - Get an existing environment. - - Returns: - Callable[[~.GetEnvironmentRequest], - Awaitable[~.Environment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_environment' not in self._stubs: - self._stubs['get_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/GetEnvironment', - request_serializer=environments.GetEnvironmentRequest.serialize, - response_deserializer=environments.Environment.deserialize, - ) - return self._stubs['get_environment'] - - @property - def list_environments(self) -> Callable[ - [environments.ListEnvironmentsRequest], - Awaitable[environments.ListEnvironmentsResponse]]: - r"""Return a callable for the list environments method over gRPC. - - List environments. - - Returns: - Callable[[~.ListEnvironmentsRequest], - Awaitable[~.ListEnvironmentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_environments' not in self._stubs: - self._stubs['list_environments'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/ListEnvironments', - request_serializer=environments.ListEnvironmentsRequest.serialize, - response_deserializer=environments.ListEnvironmentsResponse.deserialize, - ) - return self._stubs['list_environments'] - - @property - def update_environment(self) -> Callable[ - [environments.UpdateEnvironmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update environment method over gRPC. - - Update an environment. - - Returns: - Callable[[~.UpdateEnvironmentRequest], - 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_environment' not in self._stubs: - self._stubs['update_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateEnvironment', - request_serializer=environments.UpdateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_environment'] - - @property - def delete_environment(self) -> Callable[ - [environments.DeleteEnvironmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete environment method over gRPC. - - Delete an environment. - - Returns: - Callable[[~.DeleteEnvironmentRequest], - 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_environment' not in self._stubs: - self._stubs['delete_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteEnvironment', - request_serializer=environments.DeleteEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_environment'] - - @property - def execute_airflow_command(self) -> Callable[ - [environments.ExecuteAirflowCommandRequest], - Awaitable[environments.ExecuteAirflowCommandResponse]]: - r"""Return a callable for the execute airflow command method over gRPC. - - Executes Airflow CLI command. - - Returns: - Callable[[~.ExecuteAirflowCommandRequest], - Awaitable[~.ExecuteAirflowCommandResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'execute_airflow_command' not in self._stubs: - self._stubs['execute_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/ExecuteAirflowCommand', - request_serializer=environments.ExecuteAirflowCommandRequest.serialize, - response_deserializer=environments.ExecuteAirflowCommandResponse.deserialize, - ) - return self._stubs['execute_airflow_command'] - - @property - def stop_airflow_command(self) -> Callable[ - [environments.StopAirflowCommandRequest], - Awaitable[environments.StopAirflowCommandResponse]]: - r"""Return a callable for the stop airflow command method over gRPC. - - Stops Airflow CLI command execution. - - Returns: - Callable[[~.StopAirflowCommandRequest], - Awaitable[~.StopAirflowCommandResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_airflow_command' not in self._stubs: - self._stubs['stop_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/StopAirflowCommand', - request_serializer=environments.StopAirflowCommandRequest.serialize, - response_deserializer=environments.StopAirflowCommandResponse.deserialize, - ) - return self._stubs['stop_airflow_command'] - - @property - def poll_airflow_command(self) -> Callable[ - [environments.PollAirflowCommandRequest], - Awaitable[environments.PollAirflowCommandResponse]]: - r"""Return a callable for the poll airflow command method over gRPC. - - Polls Airflow CLI command execution and fetches logs. - - Returns: - Callable[[~.PollAirflowCommandRequest], - Awaitable[~.PollAirflowCommandResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'poll_airflow_command' not in self._stubs: - self._stubs['poll_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/PollAirflowCommand', - request_serializer=environments.PollAirflowCommandRequest.serialize, - response_deserializer=environments.PollAirflowCommandResponse.deserialize, - ) - return self._stubs['poll_airflow_command'] - - @property - def list_workloads(self) -> Callable[ - [environments.ListWorkloadsRequest], - Awaitable[environments.ListWorkloadsResponse]]: - r"""Return a callable for the list workloads method over gRPC. - - Lists workloads in a Cloud Composer environment. Workload is a - unit that runs a single Composer component. - - This method is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - - Returns: - Callable[[~.ListWorkloadsRequest], - Awaitable[~.ListWorkloadsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workloads' not in self._stubs: - self._stubs['list_workloads'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/ListWorkloads', - request_serializer=environments.ListWorkloadsRequest.serialize, - response_deserializer=environments.ListWorkloadsResponse.deserialize, - ) - return self._stubs['list_workloads'] - - @property - def check_upgrade(self) -> Callable[ - [environments.CheckUpgradeRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the check upgrade method over gRPC. - - Check if an upgrade operation on the environment will - succeed. - In case of problems detailed info can be found in the - returned Operation. - - Returns: - Callable[[~.CheckUpgradeRequest], - 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 'check_upgrade' not in self._stubs: - self._stubs['check_upgrade'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/CheckUpgrade', - request_serializer=environments.CheckUpgradeRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['check_upgrade'] - - @property - def create_user_workloads_secret(self) -> Callable[ - [environments.CreateUserWorkloadsSecretRequest], - Awaitable[environments.UserWorkloadsSecret]]: - r"""Return a callable for the create user workloads secret method over gRPC. - - Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.CreateUserWorkloadsSecretRequest], - Awaitable[~.UserWorkloadsSecret]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['create_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/CreateUserWorkloadsSecret', - request_serializer=environments.CreateUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['create_user_workloads_secret'] - - @property - def get_user_workloads_secret(self) -> Callable[ - [environments.GetUserWorkloadsSecretRequest], - Awaitable[environments.UserWorkloadsSecret]]: - r"""Return a callable for the get user workloads secret method over gRPC. - - Gets an existing user workloads Secret. Values of the "data" - field in the response are cleared. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.GetUserWorkloadsSecretRequest], - Awaitable[~.UserWorkloadsSecret]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['get_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/GetUserWorkloadsSecret', - request_serializer=environments.GetUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['get_user_workloads_secret'] - - @property - def list_user_workloads_secrets(self) -> Callable[ - [environments.ListUserWorkloadsSecretsRequest], - Awaitable[environments.ListUserWorkloadsSecretsResponse]]: - r"""Return a callable for the list user workloads secrets method over gRPC. - - Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.ListUserWorkloadsSecretsRequest], - Awaitable[~.ListUserWorkloadsSecretsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secrets' not in self._stubs: - self._stubs['list_user_workloads_secrets'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/ListUserWorkloadsSecrets', - request_serializer=environments.ListUserWorkloadsSecretsRequest.serialize, - response_deserializer=environments.ListUserWorkloadsSecretsResponse.deserialize, - ) - return self._stubs['list_user_workloads_secrets'] - - @property - def update_user_workloads_secret(self) -> Callable[ - [environments.UpdateUserWorkloadsSecretRequest], - Awaitable[environments.UserWorkloadsSecret]]: - r"""Return a callable for the update user workloads secret method over gRPC. - - Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.UpdateUserWorkloadsSecretRequest], - Awaitable[~.UserWorkloadsSecret]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['update_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateUserWorkloadsSecret', - request_serializer=environments.UpdateUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['update_user_workloads_secret'] - - @property - def delete_user_workloads_secret(self) -> Callable[ - [environments.DeleteUserWorkloadsSecretRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete user workloads secret method over gRPC. - - Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.DeleteUserWorkloadsSecretRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['delete_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteUserWorkloadsSecret', - request_serializer=environments.DeleteUserWorkloadsSecretRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user_workloads_secret'] - - @property - def create_user_workloads_config_map(self) -> Callable[ - [environments.CreateUserWorkloadsConfigMapRequest], - Awaitable[environments.UserWorkloadsConfigMap]]: - r"""Return a callable for the create user workloads config - map method over gRPC. - - Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.CreateUserWorkloadsConfigMapRequest], - Awaitable[~.UserWorkloadsConfigMap]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['create_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/CreateUserWorkloadsConfigMap', - request_serializer=environments.CreateUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['create_user_workloads_config_map'] - - @property - def get_user_workloads_config_map(self) -> Callable[ - [environments.GetUserWorkloadsConfigMapRequest], - Awaitable[environments.UserWorkloadsConfigMap]]: - r"""Return a callable for the get user workloads config map method over gRPC. - - Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.GetUserWorkloadsConfigMapRequest], - Awaitable[~.UserWorkloadsConfigMap]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['get_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/GetUserWorkloadsConfigMap', - request_serializer=environments.GetUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['get_user_workloads_config_map'] - - @property - def list_user_workloads_config_maps(self) -> Callable[ - [environments.ListUserWorkloadsConfigMapsRequest], - Awaitable[environments.ListUserWorkloadsConfigMapsResponse]]: - r"""Return a callable for the list user workloads config - maps method over gRPC. - - Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.ListUserWorkloadsConfigMapsRequest], - Awaitable[~.ListUserWorkloadsConfigMapsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_maps' not in self._stubs: - self._stubs['list_user_workloads_config_maps'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/ListUserWorkloadsConfigMaps', - request_serializer=environments.ListUserWorkloadsConfigMapsRequest.serialize, - response_deserializer=environments.ListUserWorkloadsConfigMapsResponse.deserialize, - ) - return self._stubs['list_user_workloads_config_maps'] - - @property - def update_user_workloads_config_map(self) -> Callable[ - [environments.UpdateUserWorkloadsConfigMapRequest], - Awaitable[environments.UserWorkloadsConfigMap]]: - r"""Return a callable for the update user workloads config - map method over gRPC. - - Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.UpdateUserWorkloadsConfigMapRequest], - Awaitable[~.UserWorkloadsConfigMap]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['update_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/UpdateUserWorkloadsConfigMap', - request_serializer=environments.UpdateUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['update_user_workloads_config_map'] - - @property - def delete_user_workloads_config_map(self) -> Callable[ - [environments.DeleteUserWorkloadsConfigMapRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete user workloads config - map method over gRPC. - - Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.DeleteUserWorkloadsConfigMapRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['delete_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/DeleteUserWorkloadsConfigMap', - request_serializer=environments.DeleteUserWorkloadsConfigMapRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user_workloads_config_map'] - - @property - def save_snapshot(self) -> Callable[ - [environments.SaveSnapshotRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the save snapshot method over gRPC. - - Creates a snapshots of a Cloud Composer environment. - - As a result of this operation, snapshot of environment's - state is stored in a location specified in the - SaveSnapshotRequest. - - Returns: - Callable[[~.SaveSnapshotRequest], - 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 'save_snapshot' not in self._stubs: - self._stubs['save_snapshot'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/SaveSnapshot', - request_serializer=environments.SaveSnapshotRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['save_snapshot'] - - @property - def load_snapshot(self) -> Callable[ - [environments.LoadSnapshotRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the load snapshot method over gRPC. - - Loads a snapshot of a Cloud Composer environment. - - As a result of this operation, a snapshot of - environment's specified in LoadSnapshotRequest is loaded - into the environment. - - Returns: - Callable[[~.LoadSnapshotRequest], - 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 'load_snapshot' not in self._stubs: - self._stubs['load_snapshot'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/LoadSnapshot', - request_serializer=environments.LoadSnapshotRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['load_snapshot'] - - @property - def database_failover(self) -> Callable[ - [environments.DatabaseFailoverRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the database failover method over gRPC. - - Triggers database failover (only for highly resilient - environments). - - Returns: - Callable[[~.DatabaseFailoverRequest], - 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 'database_failover' not in self._stubs: - self._stubs['database_failover'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/DatabaseFailover', - request_serializer=environments.DatabaseFailoverRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['database_failover'] - - @property - def fetch_database_properties(self) -> Callable[ - [environments.FetchDatabasePropertiesRequest], - Awaitable[environments.FetchDatabasePropertiesResponse]]: - r"""Return a callable for the fetch database properties method over gRPC. - - Fetches database properties. - - Returns: - Callable[[~.FetchDatabasePropertiesRequest], - Awaitable[~.FetchDatabasePropertiesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fetch_database_properties' not in self._stubs: - self._stubs['fetch_database_properties'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.Environments/FetchDatabaseProperties', - request_serializer=environments.FetchDatabasePropertiesRequest.serialize, - response_deserializer=environments.FetchDatabasePropertiesResponse.deserialize, - ) - return self._stubs['fetch_database_properties'] - - 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_environment: self._wrap_method( - self.create_environment, - default_timeout=None, - client_info=client_info, - ), - self.get_environment: self._wrap_method( - self.get_environment, - default_timeout=None, - client_info=client_info, - ), - self.list_environments: self._wrap_method( - self.list_environments, - default_timeout=None, - client_info=client_info, - ), - self.update_environment: self._wrap_method( - self.update_environment, - default_timeout=None, - client_info=client_info, - ), - self.delete_environment: self._wrap_method( - self.delete_environment, - default_timeout=None, - client_info=client_info, - ), - self.execute_airflow_command: self._wrap_method( - self.execute_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.stop_airflow_command: self._wrap_method( - self.stop_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.poll_airflow_command: self._wrap_method( - self.poll_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.list_workloads: self._wrap_method( - self.list_workloads, - default_timeout=None, - client_info=client_info, - ), - self.check_upgrade: self._wrap_method( - self.check_upgrade, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_secret: self._wrap_method( - self.create_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_secret: self._wrap_method( - self.get_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_secrets: self._wrap_method( - self.list_user_workloads_secrets, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_secret: self._wrap_method( - self.update_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_secret: self._wrap_method( - self.delete_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_config_map: self._wrap_method( - self.create_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_config_map: self._wrap_method( - self.get_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_config_maps: self._wrap_method( - self.list_user_workloads_config_maps, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_config_map: self._wrap_method( - self.update_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_config_map: self._wrap_method( - self.delete_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.save_snapshot: self._wrap_method( - self.save_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.load_snapshot: self._wrap_method( - self.load_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.database_failover: self._wrap_method( - self.database_failover, - default_timeout=None, - client_info=client_info, - ), - self.fetch_database_properties: self._wrap_method( - self.fetch_database_properties, - 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 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__ = ( - 'EnvironmentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py deleted file mode 100644 index 53477005f41e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py +++ /dev/null @@ -1,4687 +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.orchestration.airflow.service_v1.types import environments -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseEnvironmentsRestTransport -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 EnvironmentsRestInterceptor: - """Interceptor for Environments. - - 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 EnvironmentsRestTransport. - - .. code-block:: python - class MyCustomEnvironmentsInterceptor(EnvironmentsRestInterceptor): - def pre_check_upgrade(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_check_upgrade(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_user_workloads_config_map(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_user_workloads_config_map(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_user_workloads_secret(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_user_workloads_secret(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_database_failover(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_database_failover(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_user_workloads_config_map(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_user_workloads_secret(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_execute_airflow_command(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_execute_airflow_command(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_fetch_database_properties(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_fetch_database_properties(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_user_workloads_config_map(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_user_workloads_config_map(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_user_workloads_secret(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_user_workloads_secret(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_environments(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_environments(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_user_workloads_config_maps(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_user_workloads_config_maps(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_user_workloads_secrets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_user_workloads_secrets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workloads(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workloads(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_load_snapshot(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_load_snapshot(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_poll_airflow_command(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_poll_airflow_command(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_save_snapshot(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_save_snapshot(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_stop_airflow_command(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_stop_airflow_command(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_user_workloads_config_map(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_user_workloads_config_map(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_user_workloads_secret(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_user_workloads_secret(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EnvironmentsRestTransport(interceptor=MyCustomEnvironmentsInterceptor()) - client = EnvironmentsClient(transport=transport) - - - """ - def pre_check_upgrade(self, request: environments.CheckUpgradeRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CheckUpgradeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for check_upgrade - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_check_upgrade(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for check_upgrade - - DEPRECATED. Please use the `post_check_upgrade_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_check_upgrade` interceptor runs - before the `post_check_upgrade_with_metadata` interceptor. - """ - return response - - def post_check_upgrade_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for check_upgrade - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_check_upgrade_with_metadata` - interceptor in new development instead of the `post_check_upgrade` interceptor. - When both interceptors are used, this `post_check_upgrade_with_metadata` interceptor runs after the - `post_check_upgrade` interceptor. The (possibly modified) response returned by - `post_check_upgrade` will be passed to - `post_check_upgrade_with_metadata`. - """ - return response, metadata - - def pre_create_environment(self, request: environments.CreateEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_create_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_environment - - DEPRECATED. Please use the `post_create_environment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_create_environment` interceptor runs - before the `post_create_environment_with_metadata` interceptor. - """ - return response - - def post_create_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_environment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_create_environment_with_metadata` - interceptor in new development instead of the `post_create_environment` interceptor. - When both interceptors are used, this `post_create_environment_with_metadata` interceptor runs after the - `post_create_environment` interceptor. The (possibly modified) response returned by - `post_create_environment` will be passed to - `post_create_environment_with_metadata`. - """ - return response, metadata - - def pre_create_user_workloads_config_map(self, request: environments.CreateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_user_workloads_config_map - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_create_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: - """Post-rpc interceptor for create_user_workloads_config_map - - DEPRECATED. Please use the `post_create_user_workloads_config_map_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_create_user_workloads_config_map` interceptor runs - before the `post_create_user_workloads_config_map_with_metadata` interceptor. - """ - return response - - def post_create_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_user_workloads_config_map - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_create_user_workloads_config_map_with_metadata` - interceptor in new development instead of the `post_create_user_workloads_config_map` interceptor. - When both interceptors are used, this `post_create_user_workloads_config_map_with_metadata` interceptor runs after the - `post_create_user_workloads_config_map` interceptor. The (possibly modified) response returned by - `post_create_user_workloads_config_map` will be passed to - `post_create_user_workloads_config_map_with_metadata`. - """ - return response, metadata - - def pre_create_user_workloads_secret(self, request: environments.CreateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_user_workloads_secret - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_create_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: - """Post-rpc interceptor for create_user_workloads_secret - - DEPRECATED. Please use the `post_create_user_workloads_secret_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_create_user_workloads_secret` interceptor runs - before the `post_create_user_workloads_secret_with_metadata` interceptor. - """ - return response - - def post_create_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_user_workloads_secret - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_create_user_workloads_secret_with_metadata` - interceptor in new development instead of the `post_create_user_workloads_secret` interceptor. - When both interceptors are used, this `post_create_user_workloads_secret_with_metadata` interceptor runs after the - `post_create_user_workloads_secret` interceptor. The (possibly modified) response returned by - `post_create_user_workloads_secret` will be passed to - `post_create_user_workloads_secret_with_metadata`. - """ - return response, metadata - - def pre_database_failover(self, request: environments.DatabaseFailoverRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DatabaseFailoverRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for database_failover - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_database_failover(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for database_failover - - DEPRECATED. Please use the `post_database_failover_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_database_failover` interceptor runs - before the `post_database_failover_with_metadata` interceptor. - """ - return response - - def post_database_failover_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for database_failover - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_database_failover_with_metadata` - interceptor in new development instead of the `post_database_failover` interceptor. - When both interceptors are used, this `post_database_failover_with_metadata` interceptor runs after the - `post_database_failover` interceptor. The (possibly modified) response returned by - `post_database_failover` will be passed to - `post_database_failover_with_metadata`. - """ - return response, metadata - - def pre_delete_environment(self, request: environments.DeleteEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_delete_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_environment - - DEPRECATED. Please use the `post_delete_environment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_delete_environment` interceptor runs - before the `post_delete_environment_with_metadata` interceptor. - """ - return response - - def post_delete_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for delete_environment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_delete_environment_with_metadata` - interceptor in new development instead of the `post_delete_environment` interceptor. - When both interceptors are used, this `post_delete_environment_with_metadata` interceptor runs after the - `post_delete_environment` interceptor. The (possibly modified) response returned by - `post_delete_environment` will be passed to - `post_delete_environment_with_metadata`. - """ - return response, metadata - - def pre_delete_user_workloads_config_map(self, request: environments.DeleteUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_user_workloads_config_map - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def pre_delete_user_workloads_secret(self, request: environments.DeleteUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_user_workloads_secret - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def pre_execute_airflow_command(self, request: environments.ExecuteAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ExecuteAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for execute_airflow_command - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_execute_airflow_command(self, response: environments.ExecuteAirflowCommandResponse) -> environments.ExecuteAirflowCommandResponse: - """Post-rpc interceptor for execute_airflow_command - - DEPRECATED. Please use the `post_execute_airflow_command_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_execute_airflow_command` interceptor runs - before the `post_execute_airflow_command_with_metadata` interceptor. - """ - return response - - def post_execute_airflow_command_with_metadata(self, response: environments.ExecuteAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ExecuteAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for execute_airflow_command - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_execute_airflow_command_with_metadata` - interceptor in new development instead of the `post_execute_airflow_command` interceptor. - When both interceptors are used, this `post_execute_airflow_command_with_metadata` interceptor runs after the - `post_execute_airflow_command` interceptor. The (possibly modified) response returned by - `post_execute_airflow_command` will be passed to - `post_execute_airflow_command_with_metadata`. - """ - return response, metadata - - def pre_fetch_database_properties(self, request: environments.FetchDatabasePropertiesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.FetchDatabasePropertiesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for fetch_database_properties - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_fetch_database_properties(self, response: environments.FetchDatabasePropertiesResponse) -> environments.FetchDatabasePropertiesResponse: - """Post-rpc interceptor for fetch_database_properties - - DEPRECATED. Please use the `post_fetch_database_properties_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_fetch_database_properties` interceptor runs - before the `post_fetch_database_properties_with_metadata` interceptor. - """ - return response - - def post_fetch_database_properties_with_metadata(self, response: environments.FetchDatabasePropertiesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.FetchDatabasePropertiesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for fetch_database_properties - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_fetch_database_properties_with_metadata` - interceptor in new development instead of the `post_fetch_database_properties` interceptor. - When both interceptors are used, this `post_fetch_database_properties_with_metadata` interceptor runs after the - `post_fetch_database_properties` interceptor. The (possibly modified) response returned by - `post_fetch_database_properties` will be passed to - `post_fetch_database_properties_with_metadata`. - """ - return response, metadata - - def pre_get_environment(self, request: environments.GetEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_environment(self, response: environments.Environment) -> environments.Environment: - """Post-rpc interceptor for get_environment - - DEPRECATED. Please use the `post_get_environment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_get_environment` interceptor runs - before the `post_get_environment_with_metadata` interceptor. - """ - return response - - def post_get_environment_with_metadata(self, response: environments.Environment, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.Environment, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_environment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_get_environment_with_metadata` - interceptor in new development instead of the `post_get_environment` interceptor. - When both interceptors are used, this `post_get_environment_with_metadata` interceptor runs after the - `post_get_environment` interceptor. The (possibly modified) response returned by - `post_get_environment` will be passed to - `post_get_environment_with_metadata`. - """ - return response, metadata - - def pre_get_user_workloads_config_map(self, request: environments.GetUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_user_workloads_config_map - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: - """Post-rpc interceptor for get_user_workloads_config_map - - DEPRECATED. Please use the `post_get_user_workloads_config_map_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_get_user_workloads_config_map` interceptor runs - before the `post_get_user_workloads_config_map_with_metadata` interceptor. - """ - return response - - def post_get_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_user_workloads_config_map - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_get_user_workloads_config_map_with_metadata` - interceptor in new development instead of the `post_get_user_workloads_config_map` interceptor. - When both interceptors are used, this `post_get_user_workloads_config_map_with_metadata` interceptor runs after the - `post_get_user_workloads_config_map` interceptor. The (possibly modified) response returned by - `post_get_user_workloads_config_map` will be passed to - `post_get_user_workloads_config_map_with_metadata`. - """ - return response, metadata - - def pre_get_user_workloads_secret(self, request: environments.GetUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_user_workloads_secret - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: - """Post-rpc interceptor for get_user_workloads_secret - - DEPRECATED. Please use the `post_get_user_workloads_secret_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_get_user_workloads_secret` interceptor runs - before the `post_get_user_workloads_secret_with_metadata` interceptor. - """ - return response - - def post_get_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_user_workloads_secret - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_get_user_workloads_secret_with_metadata` - interceptor in new development instead of the `post_get_user_workloads_secret` interceptor. - When both interceptors are used, this `post_get_user_workloads_secret_with_metadata` interceptor runs after the - `post_get_user_workloads_secret` interceptor. The (possibly modified) response returned by - `post_get_user_workloads_secret` will be passed to - `post_get_user_workloads_secret_with_metadata`. - """ - return response, metadata - - def pre_list_environments(self, request: environments.ListEnvironmentsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListEnvironmentsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_environments - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_environments(self, response: environments.ListEnvironmentsResponse) -> environments.ListEnvironmentsResponse: - """Post-rpc interceptor for list_environments - - DEPRECATED. Please use the `post_list_environments_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_list_environments` interceptor runs - before the `post_list_environments_with_metadata` interceptor. - """ - return response - - def post_list_environments_with_metadata(self, response: environments.ListEnvironmentsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListEnvironmentsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_environments - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_list_environments_with_metadata` - interceptor in new development instead of the `post_list_environments` interceptor. - When both interceptors are used, this `post_list_environments_with_metadata` interceptor runs after the - `post_list_environments` interceptor. The (possibly modified) response returned by - `post_list_environments` will be passed to - `post_list_environments_with_metadata`. - """ - return response, metadata - - def pre_list_user_workloads_config_maps(self, request: environments.ListUserWorkloadsConfigMapsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsConfigMapsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_user_workloads_config_maps - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_user_workloads_config_maps(self, response: environments.ListUserWorkloadsConfigMapsResponse) -> environments.ListUserWorkloadsConfigMapsResponse: - """Post-rpc interceptor for list_user_workloads_config_maps - - DEPRECATED. Please use the `post_list_user_workloads_config_maps_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_list_user_workloads_config_maps` interceptor runs - before the `post_list_user_workloads_config_maps_with_metadata` interceptor. - """ - return response - - def post_list_user_workloads_config_maps_with_metadata(self, response: environments.ListUserWorkloadsConfigMapsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsConfigMapsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_user_workloads_config_maps - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_list_user_workloads_config_maps_with_metadata` - interceptor in new development instead of the `post_list_user_workloads_config_maps` interceptor. - When both interceptors are used, this `post_list_user_workloads_config_maps_with_metadata` interceptor runs after the - `post_list_user_workloads_config_maps` interceptor. The (possibly modified) response returned by - `post_list_user_workloads_config_maps` will be passed to - `post_list_user_workloads_config_maps_with_metadata`. - """ - return response, metadata - - def pre_list_user_workloads_secrets(self, request: environments.ListUserWorkloadsSecretsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsSecretsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_user_workloads_secrets - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_user_workloads_secrets(self, response: environments.ListUserWorkloadsSecretsResponse) -> environments.ListUserWorkloadsSecretsResponse: - """Post-rpc interceptor for list_user_workloads_secrets - - DEPRECATED. Please use the `post_list_user_workloads_secrets_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_list_user_workloads_secrets` interceptor runs - before the `post_list_user_workloads_secrets_with_metadata` interceptor. - """ - return response - - def post_list_user_workloads_secrets_with_metadata(self, response: environments.ListUserWorkloadsSecretsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsSecretsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_user_workloads_secrets - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_list_user_workloads_secrets_with_metadata` - interceptor in new development instead of the `post_list_user_workloads_secrets` interceptor. - When both interceptors are used, this `post_list_user_workloads_secrets_with_metadata` interceptor runs after the - `post_list_user_workloads_secrets` interceptor. The (possibly modified) response returned by - `post_list_user_workloads_secrets` will be passed to - `post_list_user_workloads_secrets_with_metadata`. - """ - return response, metadata - - def pre_list_workloads(self, request: environments.ListWorkloadsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListWorkloadsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_workloads - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_workloads(self, response: environments.ListWorkloadsResponse) -> environments.ListWorkloadsResponse: - """Post-rpc interceptor for list_workloads - - DEPRECATED. Please use the `post_list_workloads_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_list_workloads` interceptor runs - before the `post_list_workloads_with_metadata` interceptor. - """ - return response - - def post_list_workloads_with_metadata(self, response: environments.ListWorkloadsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListWorkloadsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_workloads - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_list_workloads_with_metadata` - interceptor in new development instead of the `post_list_workloads` interceptor. - When both interceptors are used, this `post_list_workloads_with_metadata` interceptor runs after the - `post_list_workloads` interceptor. The (possibly modified) response returned by - `post_list_workloads` will be passed to - `post_list_workloads_with_metadata`. - """ - return response, metadata - - def pre_load_snapshot(self, request: environments.LoadSnapshotRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.LoadSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for load_snapshot - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_load_snapshot(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for load_snapshot - - DEPRECATED. Please use the `post_load_snapshot_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_load_snapshot` interceptor runs - before the `post_load_snapshot_with_metadata` interceptor. - """ - return response - - def post_load_snapshot_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for load_snapshot - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_load_snapshot_with_metadata` - interceptor in new development instead of the `post_load_snapshot` interceptor. - When both interceptors are used, this `post_load_snapshot_with_metadata` interceptor runs after the - `post_load_snapshot` interceptor. The (possibly modified) response returned by - `post_load_snapshot` will be passed to - `post_load_snapshot_with_metadata`. - """ - return response, metadata - - def pre_poll_airflow_command(self, request: environments.PollAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.PollAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for poll_airflow_command - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_poll_airflow_command(self, response: environments.PollAirflowCommandResponse) -> environments.PollAirflowCommandResponse: - """Post-rpc interceptor for poll_airflow_command - - DEPRECATED. Please use the `post_poll_airflow_command_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_poll_airflow_command` interceptor runs - before the `post_poll_airflow_command_with_metadata` interceptor. - """ - return response - - def post_poll_airflow_command_with_metadata(self, response: environments.PollAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.PollAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for poll_airflow_command - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_poll_airflow_command_with_metadata` - interceptor in new development instead of the `post_poll_airflow_command` interceptor. - When both interceptors are used, this `post_poll_airflow_command_with_metadata` interceptor runs after the - `post_poll_airflow_command` interceptor. The (possibly modified) response returned by - `post_poll_airflow_command` will be passed to - `post_poll_airflow_command_with_metadata`. - """ - return response, metadata - - def pre_save_snapshot(self, request: environments.SaveSnapshotRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.SaveSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for save_snapshot - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_save_snapshot(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for save_snapshot - - DEPRECATED. Please use the `post_save_snapshot_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_save_snapshot` interceptor runs - before the `post_save_snapshot_with_metadata` interceptor. - """ - return response - - def post_save_snapshot_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for save_snapshot - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_save_snapshot_with_metadata` - interceptor in new development instead of the `post_save_snapshot` interceptor. - When both interceptors are used, this `post_save_snapshot_with_metadata` interceptor runs after the - `post_save_snapshot` interceptor. The (possibly modified) response returned by - `post_save_snapshot` will be passed to - `post_save_snapshot_with_metadata`. - """ - return response, metadata - - def pre_stop_airflow_command(self, request: environments.StopAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.StopAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for stop_airflow_command - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_stop_airflow_command(self, response: environments.StopAirflowCommandResponse) -> environments.StopAirflowCommandResponse: - """Post-rpc interceptor for stop_airflow_command - - DEPRECATED. Please use the `post_stop_airflow_command_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_stop_airflow_command` interceptor runs - before the `post_stop_airflow_command_with_metadata` interceptor. - """ - return response - - def post_stop_airflow_command_with_metadata(self, response: environments.StopAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.StopAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for stop_airflow_command - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_stop_airflow_command_with_metadata` - interceptor in new development instead of the `post_stop_airflow_command` interceptor. - When both interceptors are used, this `post_stop_airflow_command_with_metadata` interceptor runs after the - `post_stop_airflow_command` interceptor. The (possibly modified) response returned by - `post_stop_airflow_command` will be passed to - `post_stop_airflow_command_with_metadata`. - """ - return response, metadata - - def pre_update_environment(self, request: environments.UpdateEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_update_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_environment - - DEPRECATED. Please use the `post_update_environment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_update_environment` interceptor runs - before the `post_update_environment_with_metadata` interceptor. - """ - return response - - def post_update_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_environment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_update_environment_with_metadata` - interceptor in new development instead of the `post_update_environment` interceptor. - When both interceptors are used, this `post_update_environment_with_metadata` interceptor runs after the - `post_update_environment` interceptor. The (possibly modified) response returned by - `post_update_environment` will be passed to - `post_update_environment_with_metadata`. - """ - return response, metadata - - def pre_update_user_workloads_config_map(self, request: environments.UpdateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_user_workloads_config_map - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_update_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: - """Post-rpc interceptor for update_user_workloads_config_map - - DEPRECATED. Please use the `post_update_user_workloads_config_map_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_update_user_workloads_config_map` interceptor runs - before the `post_update_user_workloads_config_map_with_metadata` interceptor. - """ - return response - - def post_update_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_user_workloads_config_map - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_update_user_workloads_config_map_with_metadata` - interceptor in new development instead of the `post_update_user_workloads_config_map` interceptor. - When both interceptors are used, this `post_update_user_workloads_config_map_with_metadata` interceptor runs after the - `post_update_user_workloads_config_map` interceptor. The (possibly modified) response returned by - `post_update_user_workloads_config_map` will be passed to - `post_update_user_workloads_config_map_with_metadata`. - """ - return response, metadata - - def pre_update_user_workloads_secret(self, request: environments.UpdateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_user_workloads_secret - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_update_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: - """Post-rpc interceptor for update_user_workloads_secret - - DEPRECATED. Please use the `post_update_user_workloads_secret_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_update_user_workloads_secret` interceptor runs - before the `post_update_user_workloads_secret_with_metadata` interceptor. - """ - return response - - def post_update_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_user_workloads_secret - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_update_user_workloads_secret_with_metadata` - interceptor in new development instead of the `post_update_user_workloads_secret` interceptor. - When both interceptors are used, this `post_update_user_workloads_secret_with_metadata` interceptor runs after the - `post_update_user_workloads_secret` interceptor. The (possibly modified) response returned by - `post_update_user_workloads_secret` will be passed to - `post_update_user_workloads_secret_with_metadata`. - """ - return response, metadata - - 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 Environments 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 Environments 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 Environments 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 Environments 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 Environments 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 Environments server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class EnvironmentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EnvironmentsRestInterceptor - - -class EnvironmentsRestTransport(_BaseEnvironmentsRestTransport): - """REST backend synchronous transport for Environments. - - Managed Apache Airflow Environments. - - 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 = 'composer.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[EnvironmentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'composer.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 EnvironmentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/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 _CheckUpgrade(_BaseEnvironmentsRestTransport._BaseCheckUpgrade, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.CheckUpgrade") - - @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: environments.CheckUpgradeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the check upgrade method over HTTP. - - Args: - request (~.environments.CheckUpgradeRequest): - The request object. Request to check whether image - upgrade will succeed. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_http_options() - - request, metadata = self._interceptor.pre_check_upgrade(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._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.orchestration.airflow.service_v1.EnvironmentsClient.CheckUpgrade", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "CheckUpgrade", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._CheckUpgrade._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_check_upgrade(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_check_upgrade_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1.EnvironmentsClient.check_upgrade", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "CheckUpgrade", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateEnvironment(_BaseEnvironmentsRestTransport._BaseCreateEnvironment, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.CreateEnvironment") - - @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: environments.CreateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create environment method over HTTP. - - Args: - request (~.environments.CreateEnvironmentRequest): - The request object. Create a new environment. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_http_options() - - request, metadata = self._interceptor.pre_create_environment(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._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.orchestration.airflow.service_v1.EnvironmentsClient.CreateEnvironment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "CreateEnvironment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._CreateEnvironment._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_environment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_environment_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1.EnvironmentsClient.create_environment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "CreateEnvironment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.CreateUserWorkloadsConfigMap") - - @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: environments.CreateUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsConfigMap: - r"""Call the create user workloads - config map method over HTTP. - - Args: - request (~.environments.CreateUserWorkloadsConfigMapRequest): - The request object. Create user workloads ConfigMap - request. - retry (google.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: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_http_options() - - request, metadata = self._interceptor.pre_create_user_workloads_config_map(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._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.orchestration.airflow.service_v1.EnvironmentsClient.CreateUserWorkloadsConfigMap", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "CreateUserWorkloadsConfigMap", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._CreateUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() - pb_resp = environments.UserWorkloadsConfigMap.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_user_workloads_config_map(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_user_workloads_config_map_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1.EnvironmentsClient.create_user_workloads_config_map", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "CreateUserWorkloadsConfigMap", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.CreateUserWorkloadsSecret") - - @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: environments.CreateUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsSecret: - r"""Call the create user workloads - secret method over HTTP. - - Args: - request (~.environments.CreateUserWorkloadsSecretRequest): - The request object. Create user workloads Secret request. - retry (google.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: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_http_options() - - request, metadata = self._interceptor.pre_create_user_workloads_secret(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._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.orchestration.airflow.service_v1.EnvironmentsClient.CreateUserWorkloadsSecret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "CreateUserWorkloadsSecret", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._CreateUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() - pb_resp = environments.UserWorkloadsSecret.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_user_workloads_secret(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_user_workloads_secret_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1.EnvironmentsClient.create_user_workloads_secret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "CreateUserWorkloadsSecret", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DatabaseFailover(_BaseEnvironmentsRestTransport._BaseDatabaseFailover, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.DatabaseFailover") - - @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: environments.DatabaseFailoverRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the database failover method over HTTP. - - Args: - request (~.environments.DatabaseFailoverRequest): - The request object. Request to trigger database failover - (only for highly resilient - environments). - retry (google.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 = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_http_options() - - request, metadata = self._interceptor.pre_database_failover(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._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.orchestration.airflow.service_v1.EnvironmentsClient.DatabaseFailover", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "DatabaseFailover", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._DatabaseFailover._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_database_failover(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_database_failover_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1.EnvironmentsClient.database_failover", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "DatabaseFailover", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteEnvironment(_BaseEnvironmentsRestTransport._BaseDeleteEnvironment, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.DeleteEnvironment") - - @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: environments.DeleteEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete environment method over HTTP. - - Args: - request (~.environments.DeleteEnvironmentRequest): - The request object. Delete an environment. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_http_options() - - request, metadata = self._interceptor.pre_delete_environment(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._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.orchestration.airflow.service_v1.EnvironmentsClient.DeleteEnvironment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "DeleteEnvironment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._DeleteEnvironment._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_environment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_environment_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1.EnvironmentsClient.delete_environment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "DeleteEnvironment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.DeleteUserWorkloadsConfigMap") - - @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: environments.DeleteUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete user workloads - config map method over HTTP. - - Args: - request (~.environments.DeleteUserWorkloadsConfigMapRequest): - The request object. Delete user workloads ConfigMap - request. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_http_options() - - request, metadata = self._interceptor.pre_delete_user_workloads_config_map(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._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.orchestration.airflow.service_v1.EnvironmentsClient.DeleteUserWorkloadsConfigMap", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "DeleteUserWorkloadsConfigMap", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._DeleteUserWorkloadsConfigMap._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) - - class _DeleteUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.DeleteUserWorkloadsSecret") - - @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: environments.DeleteUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete user workloads - secret method over HTTP. - - Args: - request (~.environments.DeleteUserWorkloadsSecretRequest): - The request object. Delete user workloads Secret request. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_http_options() - - request, metadata = self._interceptor.pre_delete_user_workloads_secret(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._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.orchestration.airflow.service_v1.EnvironmentsClient.DeleteUserWorkloadsSecret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "DeleteUserWorkloadsSecret", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._DeleteUserWorkloadsSecret._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) - - class _ExecuteAirflowCommand(_BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.ExecuteAirflowCommand") - - @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: environments.ExecuteAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.ExecuteAirflowCommandResponse: - r"""Call the execute airflow command method over HTTP. - - Args: - request (~.environments.ExecuteAirflowCommandRequest): - The request object. Execute Airflow Command request. - retry (google.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: - ~.environments.ExecuteAirflowCommandResponse: - Response to - ExecuteAirflowCommandRequest. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_http_options() - - request, metadata = self._interceptor.pre_execute_airflow_command(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._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.orchestration.airflow.service_v1.EnvironmentsClient.ExecuteAirflowCommand", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ExecuteAirflowCommand", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._ExecuteAirflowCommand._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 = environments.ExecuteAirflowCommandResponse() - pb_resp = environments.ExecuteAirflowCommandResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_execute_airflow_command(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_execute_airflow_command_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.ExecuteAirflowCommandResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.execute_airflow_command", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ExecuteAirflowCommand", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _FetchDatabaseProperties(_BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.FetchDatabaseProperties") - - @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: environments.FetchDatabasePropertiesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.FetchDatabasePropertiesResponse: - r"""Call the fetch database properties method over HTTP. - - Args: - request (~.environments.FetchDatabasePropertiesRequest): - The request object. Request to fetch properties of - environment's database. - retry (google.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: - ~.environments.FetchDatabasePropertiesResponse: - Response for - FetchDatabasePropertiesRequest. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_http_options() - - request, metadata = self._interceptor.pre_fetch_database_properties(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._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.orchestration.airflow.service_v1.EnvironmentsClient.FetchDatabaseProperties", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "FetchDatabaseProperties", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._FetchDatabaseProperties._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 = environments.FetchDatabasePropertiesResponse() - pb_resp = environments.FetchDatabasePropertiesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_fetch_database_properties(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_fetch_database_properties_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.FetchDatabasePropertiesResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.fetch_database_properties", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "FetchDatabaseProperties", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetEnvironment(_BaseEnvironmentsRestTransport._BaseGetEnvironment, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.GetEnvironment") - - @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: environments.GetEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.Environment: - r"""Call the get environment method over HTTP. - - Args: - request (~.environments.GetEnvironmentRequest): - The request object. Get an environment. - retry (google.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: - ~.environments.Environment: - An environment for running - orchestration tasks. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_http_options() - - request, metadata = self._interceptor.pre_get_environment(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseGetEnvironment._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.orchestration.airflow.service_v1.EnvironmentsClient.GetEnvironment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "GetEnvironment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._GetEnvironment._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 = environments.Environment() - pb_resp = environments.Environment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_environment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_environment_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.Environment.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.orchestration.airflow.service_v1.EnvironmentsClient.get_environment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "GetEnvironment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.GetUserWorkloadsConfigMap") - - @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: environments.GetUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsConfigMap: - r"""Call the get user workloads config - map method over HTTP. - - Args: - request (~.environments.GetUserWorkloadsConfigMapRequest): - The request object. Get user workloads ConfigMap request. - retry (google.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: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_http_options() - - request, metadata = self._interceptor.pre_get_user_workloads_config_map(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._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.orchestration.airflow.service_v1.EnvironmentsClient.GetUserWorkloadsConfigMap", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "GetUserWorkloadsConfigMap", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._GetUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() - pb_resp = environments.UserWorkloadsConfigMap.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_user_workloads_config_map(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_user_workloads_config_map_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1.EnvironmentsClient.get_user_workloads_config_map", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "GetUserWorkloadsConfigMap", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.GetUserWorkloadsSecret") - - @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: environments.GetUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsSecret: - r"""Call the get user workloads secret method over HTTP. - - Args: - request (~.environments.GetUserWorkloadsSecretRequest): - The request object. Get user workloads Secret request. - retry (google.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: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_http_options() - - request, metadata = self._interceptor.pre_get_user_workloads_secret(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._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.orchestration.airflow.service_v1.EnvironmentsClient.GetUserWorkloadsSecret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "GetUserWorkloadsSecret", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._GetUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() - pb_resp = environments.UserWorkloadsSecret.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_user_workloads_secret(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_user_workloads_secret_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1.EnvironmentsClient.get_user_workloads_secret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "GetUserWorkloadsSecret", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListEnvironments(_BaseEnvironmentsRestTransport._BaseListEnvironments, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.ListEnvironments") - - @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: environments.ListEnvironmentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.ListEnvironmentsResponse: - r"""Call the list environments method over HTTP. - - Args: - request (~.environments.ListEnvironmentsRequest): - The request object. List environments in a project and - location. - retry (google.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: - ~.environments.ListEnvironmentsResponse: - The environments in a project and - location. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseListEnvironments._get_http_options() - - request, metadata = self._interceptor.pre_list_environments(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseListEnvironments._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseListEnvironments._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.orchestration.airflow.service_v1.EnvironmentsClient.ListEnvironments", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ListEnvironments", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._ListEnvironments._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 = environments.ListEnvironmentsResponse() - pb_resp = environments.ListEnvironmentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_environments(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_environments_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.ListEnvironmentsResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.list_environments", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ListEnvironments", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListUserWorkloadsConfigMaps(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.ListUserWorkloadsConfigMaps") - - @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: environments.ListUserWorkloadsConfigMapsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.ListUserWorkloadsConfigMapsResponse: - r"""Call the list user workloads - config maps method over HTTP. - - Args: - request (~.environments.ListUserWorkloadsConfigMapsRequest): - The request object. List user workloads ConfigMaps - request. - retry (google.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: - ~.environments.ListUserWorkloadsConfigMapsResponse: - The user workloads ConfigMaps for a - given environment. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_http_options() - - request, metadata = self._interceptor.pre_list_user_workloads_config_maps(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._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.orchestration.airflow.service_v1.EnvironmentsClient.ListUserWorkloadsConfigMaps", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ListUserWorkloadsConfigMaps", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._ListUserWorkloadsConfigMaps._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 = environments.ListUserWorkloadsConfigMapsResponse() - pb_resp = environments.ListUserWorkloadsConfigMapsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_user_workloads_config_maps(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_user_workloads_config_maps_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.ListUserWorkloadsConfigMapsResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.list_user_workloads_config_maps", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ListUserWorkloadsConfigMaps", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListUserWorkloadsSecrets(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.ListUserWorkloadsSecrets") - - @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: environments.ListUserWorkloadsSecretsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.ListUserWorkloadsSecretsResponse: - r"""Call the list user workloads - secrets method over HTTP. - - Args: - request (~.environments.ListUserWorkloadsSecretsRequest): - The request object. List user workloads Secrets request. - retry (google.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: - ~.environments.ListUserWorkloadsSecretsResponse: - The user workloads Secrets for a - given environment. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_http_options() - - request, metadata = self._interceptor.pre_list_user_workloads_secrets(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._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.orchestration.airflow.service_v1.EnvironmentsClient.ListUserWorkloadsSecrets", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ListUserWorkloadsSecrets", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._ListUserWorkloadsSecrets._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 = environments.ListUserWorkloadsSecretsResponse() - pb_resp = environments.ListUserWorkloadsSecretsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_user_workloads_secrets(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_user_workloads_secrets_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.ListUserWorkloadsSecretsResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.list_user_workloads_secrets", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ListUserWorkloadsSecrets", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListWorkloads(_BaseEnvironmentsRestTransport._BaseListWorkloads, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.ListWorkloads") - - @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: environments.ListWorkloadsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.ListWorkloadsResponse: - r"""Call the list workloads method over HTTP. - - Args: - request (~.environments.ListWorkloadsRequest): - The request object. Request for listing workloads in a - Cloud Composer environment. - retry (google.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: - ~.environments.ListWorkloadsResponse: - Response to ListWorkloadsRequest. - """ - - http_options = _BaseEnvironmentsRestTransport._BaseListWorkloads._get_http_options() - - request, metadata = self._interceptor.pre_list_workloads(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseListWorkloads._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseListWorkloads._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.orchestration.airflow.service_v1.EnvironmentsClient.ListWorkloads", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ListWorkloads", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._ListWorkloads._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 = environments.ListWorkloadsResponse() - pb_resp = environments.ListWorkloadsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_workloads(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_workloads_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.ListWorkloadsResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.list_workloads", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ListWorkloads", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _LoadSnapshot(_BaseEnvironmentsRestTransport._BaseLoadSnapshot, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.LoadSnapshot") - - @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: environments.LoadSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the load snapshot method over HTTP. - - Args: - request (~.environments.LoadSnapshotRequest): - The request object. Request to load a snapshot into a - Cloud Composer environment. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_http_options() - - request, metadata = self._interceptor.pre_load_snapshot(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._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.orchestration.airflow.service_v1.EnvironmentsClient.LoadSnapshot", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "LoadSnapshot", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._LoadSnapshot._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_load_snapshot(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_load_snapshot_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1.EnvironmentsClient.load_snapshot", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "LoadSnapshot", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _PollAirflowCommand(_BaseEnvironmentsRestTransport._BasePollAirflowCommand, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.PollAirflowCommand") - - @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: environments.PollAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.PollAirflowCommandResponse: - r"""Call the poll airflow command method over HTTP. - - Args: - request (~.environments.PollAirflowCommandRequest): - The request object. Poll Airflow Command request. - retry (google.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: - ~.environments.PollAirflowCommandResponse: - Response to - PollAirflowCommandRequest. - - """ - - http_options = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_http_options() - - request, metadata = self._interceptor.pre_poll_airflow_command(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._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.orchestration.airflow.service_v1.EnvironmentsClient.PollAirflowCommand", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "PollAirflowCommand", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._PollAirflowCommand._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 = environments.PollAirflowCommandResponse() - pb_resp = environments.PollAirflowCommandResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_poll_airflow_command(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_poll_airflow_command_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.PollAirflowCommandResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.poll_airflow_command", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "PollAirflowCommand", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _SaveSnapshot(_BaseEnvironmentsRestTransport._BaseSaveSnapshot, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.SaveSnapshot") - - @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: environments.SaveSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the save snapshot method over HTTP. - - Args: - request (~.environments.SaveSnapshotRequest): - The request object. Request to create a snapshot of a - Cloud Composer environment. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_http_options() - - request, metadata = self._interceptor.pre_save_snapshot(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._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.orchestration.airflow.service_v1.EnvironmentsClient.SaveSnapshot", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "SaveSnapshot", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._SaveSnapshot._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_save_snapshot(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_save_snapshot_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1.EnvironmentsClient.save_snapshot", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "SaveSnapshot", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _StopAirflowCommand(_BaseEnvironmentsRestTransport._BaseStopAirflowCommand, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.StopAirflowCommand") - - @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: environments.StopAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.StopAirflowCommandResponse: - r"""Call the stop airflow command method over HTTP. - - Args: - request (~.environments.StopAirflowCommandRequest): - The request object. Stop Airflow Command request. - retry (google.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: - ~.environments.StopAirflowCommandResponse: - Response to - StopAirflowCommandRequest. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_http_options() - - request, metadata = self._interceptor.pre_stop_airflow_command(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._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.orchestration.airflow.service_v1.EnvironmentsClient.StopAirflowCommand", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "StopAirflowCommand", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._StopAirflowCommand._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 = environments.StopAirflowCommandResponse() - pb_resp = environments.StopAirflowCommandResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_stop_airflow_command(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_stop_airflow_command_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.StopAirflowCommandResponse.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.orchestration.airflow.service_v1.EnvironmentsClient.stop_airflow_command", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "StopAirflowCommand", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateEnvironment(_BaseEnvironmentsRestTransport._BaseUpdateEnvironment, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.UpdateEnvironment") - - @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: environments.UpdateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update environment method over HTTP. - - Args: - request (~.environments.UpdateEnvironmentRequest): - The request object. Update an environment. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_http_options() - - request, metadata = self._interceptor.pre_update_environment(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._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.orchestration.airflow.service_v1.EnvironmentsClient.UpdateEnvironment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "UpdateEnvironment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._UpdateEnvironment._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_environment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_environment_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1.EnvironmentsClient.update_environment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "UpdateEnvironment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.UpdateUserWorkloadsConfigMap") - - @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: environments.UpdateUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsConfigMap: - r"""Call the update user workloads - config map method over HTTP. - - Args: - request (~.environments.UpdateUserWorkloadsConfigMapRequest): - The request object. Update user workloads ConfigMap - request. - retry (google.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: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_http_options() - - request, metadata = self._interceptor.pre_update_user_workloads_config_map(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._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.orchestration.airflow.service_v1.EnvironmentsClient.UpdateUserWorkloadsConfigMap", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "UpdateUserWorkloadsConfigMap", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._UpdateUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() - pb_resp = environments.UserWorkloadsConfigMap.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_user_workloads_config_map(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_user_workloads_config_map_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1.EnvironmentsClient.update_user_workloads_config_map", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "UpdateUserWorkloadsConfigMap", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.UpdateUserWorkloadsSecret") - - @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: environments.UpdateUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsSecret: - r"""Call the update user workloads - secret method over HTTP. - - Args: - request (~.environments.UpdateUserWorkloadsSecretRequest): - The request object. Update user workloads Secret request. - retry (google.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: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_http_options() - - request, metadata = self._interceptor.pre_update_user_workloads_secret(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._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.orchestration.airflow.service_v1.EnvironmentsClient.UpdateUserWorkloadsSecret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "UpdateUserWorkloadsSecret", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._UpdateUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() - pb_resp = environments.UserWorkloadsSecret.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_user_workloads_secret(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_user_workloads_secret_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1.EnvironmentsClient.update_user_workloads_secret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "UpdateUserWorkloadsSecret", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def check_upgrade(self) -> Callable[ - [environments.CheckUpgradeRequest], - 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._CheckUpgrade(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_environment(self) -> Callable[ - [environments.CreateEnvironmentRequest], - 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._CreateEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_user_workloads_config_map(self) -> Callable[ - [environments.CreateUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - # 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._CreateUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_user_workloads_secret(self) -> Callable[ - [environments.CreateUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - # 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._CreateUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore - - @property - def database_failover(self) -> Callable[ - [environments.DatabaseFailoverRequest], - 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._DatabaseFailover(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_environment(self) -> Callable[ - [environments.DeleteEnvironmentRequest], - 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._DeleteEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_user_workloads_config_map(self) -> Callable[ - [environments.DeleteUserWorkloadsConfigMapRequest], - empty_pb2.Empty]: - # 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._DeleteUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_user_workloads_secret(self) -> Callable[ - [environments.DeleteUserWorkloadsSecretRequest], - empty_pb2.Empty]: - # 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._DeleteUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore - - @property - def execute_airflow_command(self) -> Callable[ - [environments.ExecuteAirflowCommandRequest], - environments.ExecuteAirflowCommandResponse]: - # 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._ExecuteAirflowCommand(self._session, self._host, self._interceptor) # type: ignore - - @property - def fetch_database_properties(self) -> Callable[ - [environments.FetchDatabasePropertiesRequest], - environments.FetchDatabasePropertiesResponse]: - # 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._FetchDatabaseProperties(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_environment(self) -> Callable[ - [environments.GetEnvironmentRequest], - environments.Environment]: - # 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._GetEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_user_workloads_config_map(self) -> Callable[ - [environments.GetUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - # 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._GetUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_user_workloads_secret(self) -> Callable[ - [environments.GetUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - # 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._GetUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_environments(self) -> Callable[ - [environments.ListEnvironmentsRequest], - environments.ListEnvironmentsResponse]: - # 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._ListEnvironments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_user_workloads_config_maps(self) -> Callable[ - [environments.ListUserWorkloadsConfigMapsRequest], - environments.ListUserWorkloadsConfigMapsResponse]: - # 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._ListUserWorkloadsConfigMaps(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_user_workloads_secrets(self) -> Callable[ - [environments.ListUserWorkloadsSecretsRequest], - environments.ListUserWorkloadsSecretsResponse]: - # 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._ListUserWorkloadsSecrets(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workloads(self) -> Callable[ - [environments.ListWorkloadsRequest], - environments.ListWorkloadsResponse]: - # 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._ListWorkloads(self._session, self._host, self._interceptor) # type: ignore - - @property - def load_snapshot(self) -> Callable[ - [environments.LoadSnapshotRequest], - 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._LoadSnapshot(self._session, self._host, self._interceptor) # type: ignore - - @property - def poll_airflow_command(self) -> Callable[ - [environments.PollAirflowCommandRequest], - environments.PollAirflowCommandResponse]: - # 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._PollAirflowCommand(self._session, self._host, self._interceptor) # type: ignore - - @property - def save_snapshot(self) -> Callable[ - [environments.SaveSnapshotRequest], - 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._SaveSnapshot(self._session, self._host, self._interceptor) # type: ignore - - @property - def stop_airflow_command(self) -> Callable[ - [environments.StopAirflowCommandRequest], - environments.StopAirflowCommandResponse]: - # 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._StopAirflowCommand(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_environment(self) -> Callable[ - [environments.UpdateEnvironmentRequest], - 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._UpdateEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_user_workloads_config_map(self) -> Callable[ - [environments.UpdateUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - # 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._UpdateUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_user_workloads_secret(self) -> Callable[ - [environments.UpdateUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - # 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._UpdateUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseEnvironmentsRestTransport._BaseDeleteOperation, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseDeleteOperation._get_http_options() - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1.EnvironmentsClient.DeleteOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._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(_BaseEnvironmentsRestTransport._BaseGetOperation, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1.EnvironmentsClient.GetOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._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.orchestration.airflow.service_v1.EnvironmentsAsyncClient.GetOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "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(_BaseEnvironmentsRestTransport._BaseListOperations, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1.EnvironmentsClient.ListOperations", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._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.orchestration.airflow.service_v1.EnvironmentsAsyncClient.ListOperations", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.Environments", - "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__=( - 'EnvironmentsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest_base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest_base.py deleted file mode 100644 index 288d7319af97..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest_base.py +++ /dev/null @@ -1,1082 +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 EnvironmentsTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.orchestration.airflow.service_v1.types import environments -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseEnvironmentsRestTransport(EnvironmentsTransport): - """Base REST backend transport for Environments. - - 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 = 'composer.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: 'composer.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 _BaseCheckUpgrade: - 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/{environment=projects/*/locations/*/environments/*}:checkUpgrade', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.CheckUpgradeRequest.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=True - ) - 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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateEnvironment: - 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/{parent=projects/*/locations/*}/environments', - 'body': 'environment', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.CreateEnvironmentRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateUserWorkloadsConfigMap: - 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/*/environments/*}/userWorkloadsConfigMaps', - 'body': 'user_workloads_config_map', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.CreateUserWorkloadsConfigMapRequest.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=True - ) - 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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateUserWorkloadsSecret: - 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/*/environments/*}/userWorkloadsSecrets', - 'body': 'user_workloads_secret', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.CreateUserWorkloadsSecretRequest.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=True - ) - 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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDatabaseFailover: - 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/{environment=projects/*/locations/*/environments/*}:databaseFailover', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.DatabaseFailoverRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteEnvironment: - 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/*/environments/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.DeleteEnvironmentRequest.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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteUserWorkloadsConfigMap: - 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/*/environments/*/userWorkloadsConfigMaps/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.DeleteUserWorkloadsConfigMapRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteUserWorkloadsSecret: - 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/*/environments/*/userWorkloadsSecrets/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.DeleteUserWorkloadsSecretRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseExecuteAirflowCommand: - 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/{environment=projects/*/locations/*/environments/*}:executeAirflowCommand', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.ExecuteAirflowCommandRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseFetchDatabaseProperties: - 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/{environment=projects/*/locations/*/environments/*}:fetchDatabaseProperties', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.FetchDatabasePropertiesRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetEnvironment: - 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/*/environments/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.GetEnvironmentRequest.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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetUserWorkloadsConfigMap: - 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/*/environments/*/userWorkloadsConfigMaps/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.GetUserWorkloadsConfigMapRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetUserWorkloadsSecret: - 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/*/environments/*/userWorkloadsSecrets/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.GetUserWorkloadsSecretRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListEnvironments: - 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/{parent=projects/*/locations/*}/environments', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.ListEnvironmentsRequest.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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListUserWorkloadsConfigMaps: - 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/*/environments/*}/userWorkloadsConfigMaps', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.ListUserWorkloadsConfigMapsRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListUserWorkloadsSecrets: - 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/*/environments/*}/userWorkloadsSecrets', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.ListUserWorkloadsSecretsRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListWorkloads: - 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/*/environments/*}/workloads', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.ListWorkloadsRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseListWorkloads._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseLoadSnapshot: - 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/{environment=projects/*/locations/*/environments/*}:loadSnapshot', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.LoadSnapshotRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BasePollAirflowCommand: - 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/{environment=projects/*/locations/*/environments/*}:pollAirflowCommand', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.PollAirflowCommandRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseSaveSnapshot: - 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/{environment=projects/*/locations/*/environments/*}:saveSnapshot', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.SaveSnapshotRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStopAirflowCommand: - 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/{environment=projects/*/locations/*/environments/*}:stopAirflowCommand', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.StopAirflowCommandRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateEnvironment: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{name=projects/*/locations/*/environments/*}', - 'body': 'environment', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.UpdateEnvironmentRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateUserWorkloadsConfigMap: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', - 'body': 'user_workloads_config_map', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.UpdateUserWorkloadsConfigMapRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateUserWorkloadsSecret: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', - 'body': 'user_workloads_secret', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.UpdateUserWorkloadsSecretRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - 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__=( - '_BaseEnvironmentsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/__init__.py deleted file mode 100644 index cf004e25ae3f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/__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 ImageVersionsClient -from .async_client import ImageVersionsAsyncClient - -__all__ = ( - 'ImageVersionsClient', - 'ImageVersionsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/async_client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/async_client.py deleted file mode 100644 index 91ef6c10b56f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/async_client.py +++ /dev/null @@ -1,536 +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.orchestration.airflow.service_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.cloud.orchestration.airflow.service_v1.services.image_versions import pagers -from google.cloud.orchestration.airflow.service_v1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import ImageVersionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ImageVersionsGrpcAsyncIOTransport -from .client import ImageVersionsClient - -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 ImageVersionsAsyncClient: - """Readonly service to query available ImageVersions.""" - - _client: ImageVersionsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ImageVersionsClient._DEFAULT_UNIVERSE - - common_billing_account_path = staticmethod(ImageVersionsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ImageVersionsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ImageVersionsClient.common_folder_path) - parse_common_folder_path = staticmethod(ImageVersionsClient.parse_common_folder_path) - common_organization_path = staticmethod(ImageVersionsClient.common_organization_path) - parse_common_organization_path = staticmethod(ImageVersionsClient.parse_common_organization_path) - common_project_path = staticmethod(ImageVersionsClient.common_project_path) - parse_common_project_path = staticmethod(ImageVersionsClient.parse_common_project_path) - common_location_path = staticmethod(ImageVersionsClient.common_location_path) - parse_common_location_path = staticmethod(ImageVersionsClient.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: - ImageVersionsAsyncClient: The constructed client. - """ - return ImageVersionsClient.from_service_account_info.__func__(ImageVersionsAsyncClient, 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: - ImageVersionsAsyncClient: The constructed client. - """ - return ImageVersionsClient.from_service_account_file.__func__(ImageVersionsAsyncClient, 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 ImageVersionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ImageVersionsTransport: - """Returns the transport used by the client instance. - - Returns: - ImageVersionsTransport: 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 = ImageVersionsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ImageVersionsTransport, Callable[..., ImageVersionsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the image versions 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,ImageVersionsTransport,Callable[..., ImageVersionsTransport]]]): - 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 ImageVersionsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ImageVersionsClient( - 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.orchestration.airflow.service_v1.ImageVersionsAsyncClient`.", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "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.orchestration.airflow.service.v1.ImageVersions", - "credentialsType": None, - } - ) - - async def list_image_versions(self, - request: Optional[Union[image_versions.ListImageVersionsRequest, 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.ListImageVersionsAsyncPager: - r"""List ImageVersions for provided 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.orchestration.airflow import service_v1 - - async def sample_list_image_versions(): - # Create a client - client = service_v1.ImageVersionsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ListImageVersionsRequest( - ) - - # Make the request - page_result = client.list_image_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest, dict]]): - The request object. List ImageVersions in a project and - location. - parent (:class:`str`): - List ImageVersions in the given - project and location, in the form: - "projects/{projectId}/locations/{locationId}" - - 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.orchestration.airflow.service_v1.services.image_versions.pagers.ListImageVersionsAsyncPager: - The ImageVersions in a project and - location. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, image_versions.ListImageVersionsRequest): - request = image_versions.ListImageVersionsRequest(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_image_versions] - - # 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.ListImageVersionsAsyncPager( - method=rpc, - request=request, - response=response, - 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 __aenter__(self) -> "ImageVersionsAsyncClient": - 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__ = ( - "ImageVersionsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py deleted file mode 100644 index 38be91879394..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py +++ /dev/null @@ -1,897 +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 http import HTTPStatus -import json -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.orchestration.airflow.service_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.cloud.orchestration.airflow.service_v1.services.image_versions import pagers -from google.cloud.orchestration.airflow.service_v1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import ImageVersionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ImageVersionsGrpcTransport -from .transports.grpc_asyncio import ImageVersionsGrpcAsyncIOTransport -from .transports.rest import ImageVersionsRestTransport - - -class ImageVersionsClientMeta(type): - """Metaclass for the ImageVersions 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[ImageVersionsTransport]] - _transport_registry["grpc"] = ImageVersionsGrpcTransport - _transport_registry["grpc_asyncio"] = ImageVersionsGrpcAsyncIOTransport - _transport_registry["rest"] = ImageVersionsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ImageVersionsTransport]: - """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 ImageVersionsClient(metaclass=ImageVersionsClientMeta): - """Readonly service to query available ImageVersions.""" - - @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 = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "composer.{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: - ImageVersionsClient: 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: - ImageVersionsClient: 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) -> ImageVersionsTransport: - """Returns the transport used by the client instance. - - Returns: - ImageVersionsTransport: The transport used by the client - instance. - """ - return self._transport - - @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 = ImageVersionsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ImageVersionsClient._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 = ImageVersionsClient._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 - - def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError - ) -> None: - """Adds credential info string to error details for 401/403/404 errors. - - Args: - error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. - """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @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, ImageVersionsTransport, Callable[..., ImageVersionsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the image versions 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,ImageVersionsTransport,Callable[..., ImageVersionsTransport]]]): - 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 ImageVersionsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ImageVersionsClient._read_environment_variables() - self._client_cert_source = ImageVersionsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ImageVersionsClient._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, ImageVersionsTransport) - if transport_provided: - # transport is a ImageVersionsTransport 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(ImageVersionsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ImageVersionsClient._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[ImageVersionsTransport], Callable[..., ImageVersionsTransport]] = ( - ImageVersionsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ImageVersionsTransport], 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.orchestration.airflow.service_v1.ImageVersionsClient`.", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "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.orchestration.airflow.service.v1.ImageVersions", - "credentialsType": None, - } - ) - - def list_image_versions(self, - request: Optional[Union[image_versions.ListImageVersionsRequest, 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.ListImageVersionsPager: - r"""List ImageVersions for provided 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.orchestration.airflow import service_v1 - - def sample_list_image_versions(): - # Create a client - client = service_v1.ImageVersionsClient() - - # Initialize request argument(s) - request = service_v1.ListImageVersionsRequest( - ) - - # Make the request - page_result = client.list_image_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest, dict]): - The request object. List ImageVersions in a project and - location. - parent (str): - List ImageVersions in the given - project and location, in the form: - "projects/{projectId}/locations/{locationId}" - - 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.orchestration.airflow.service_v1.services.image_versions.pagers.ListImageVersionsPager: - The ImageVersions in a project and - location. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, image_versions.ListImageVersionsRequest): - request = image_versions.ListImageVersionsRequest(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_image_versions] - - # 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.ListImageVersionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ImageVersionsClient": - 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() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - 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() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - 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,) - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ImageVersionsClient", -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/pagers.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/pagers.py deleted file mode 100644 index 2dcaf6fac525..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/pagers.py +++ /dev/null @@ -1,166 +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.orchestration.airflow.service_v1.types import image_versions - - -class ListImageVersionsPager: - """A pager for iterating through ``list_image_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``image_versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListImageVersions`` requests and continue to iterate - through the ``image_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse` - 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[..., image_versions.ListImageVersionsResponse], - request: image_versions.ListImageVersionsRequest, - response: image_versions.ListImageVersionsResponse, - *, - 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.orchestration.airflow.service_v1.types.ListImageVersionsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse): - 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 = image_versions.ListImageVersionsRequest(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[image_versions.ListImageVersionsResponse]: - 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[image_versions.ImageVersion]: - for page in self.pages: - yield from page.image_versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListImageVersionsAsyncPager: - """A pager for iterating through ``list_image_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``image_versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListImageVersions`` requests and continue to iterate - through the ``image_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse` - 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[image_versions.ListImageVersionsResponse]], - request: image_versions.ListImageVersionsRequest, - response: image_versions.ListImageVersionsResponse, - *, - 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.orchestration.airflow.service_v1.types.ListImageVersionsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse): - 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 = image_versions.ListImageVersionsRequest(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[image_versions.ListImageVersionsResponse]: - 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[image_versions.ImageVersion]: - async def async_generator(): - async for page in self.pages: - for response in page.image_versions: - 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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/README.rst deleted file mode 100644 index 8d4dc0e29401..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ImageVersionsTransport` is the ABC for all transports. -- public child `ImageVersionsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ImageVersionsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseImageVersionsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ImageVersionsRestTransport` 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-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/__init__.py deleted file mode 100644 index 5ab47c371986..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/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 ImageVersionsTransport -from .grpc import ImageVersionsGrpcTransport -from .grpc_asyncio import ImageVersionsGrpcAsyncIOTransport -from .rest import ImageVersionsRestTransport -from .rest import ImageVersionsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ImageVersionsTransport]] -_transport_registry['grpc'] = ImageVersionsGrpcTransport -_transport_registry['grpc_asyncio'] = ImageVersionsGrpcAsyncIOTransport -_transport_registry['rest'] = ImageVersionsRestTransport - -__all__ = ( - 'ImageVersionsTransport', - 'ImageVersionsGrpcTransport', - 'ImageVersionsGrpcAsyncIOTransport', - 'ImageVersionsRestTransport', - 'ImageVersionsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/base.py deleted file mode 100644 index 09eff503a215..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/base.py +++ /dev/null @@ -1,197 +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.orchestration.airflow.service_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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.orchestration.airflow.service_v1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ImageVersionsTransport(abc.ABC): - """Abstract transport class for ImageVersions.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'composer.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: 'composer.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_image_versions: gapic_v1.method.wrap_method( - self.list_image_versions, - 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 list_image_versions(self) -> Callable[ - [image_versions.ListImageVersionsRequest], - Union[ - image_versions.ListImageVersionsResponse, - Awaitable[image_versions.ListImageVersionsResponse] - ]]: - 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 delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ImageVersionsTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc.py deleted file mode 100644 index 8c30881bbf8d..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc.py +++ /dev/null @@ -1,402 +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 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.orchestration.airflow.service_v1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageVersionsTransport, 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.orchestration.airflow.service.v1.ImageVersions", - "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.orchestration.airflow.service.v1.ImageVersions", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ImageVersionsGrpcTransport(ImageVersionsTransport): - """gRPC backend transport for ImageVersions. - - Readonly service to query available ImageVersions. - - 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 = 'composer.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: 'composer.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] = {} - - 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 = 'composer.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 list_image_versions(self) -> Callable[ - [image_versions.ListImageVersionsRequest], - image_versions.ListImageVersionsResponse]: - r"""Return a callable for the list image versions method over gRPC. - - List ImageVersions for provided location. - - Returns: - Callable[[~.ListImageVersionsRequest], - ~.ListImageVersionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_image_versions' not in self._stubs: - self._stubs['list_image_versions'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.ImageVersions/ListImageVersions', - request_serializer=image_versions.ListImageVersionsRequest.serialize, - response_deserializer=image_versions.ListImageVersionsResponse.deserialize, - ) - return self._stubs['list_image_versions'] - - 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 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__ = ( - 'ImageVersionsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc_asyncio.py deleted file mode 100644 index d16d24e25d79..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/grpc_asyncio.py +++ /dev/null @@ -1,437 +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.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.orchestration.airflow.service_v1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO -from .grpc import ImageVersionsGrpcTransport - -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.orchestration.airflow.service.v1.ImageVersions", - "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.orchestration.airflow.service.v1.ImageVersions", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ImageVersionsGrpcAsyncIOTransport(ImageVersionsTransport): - """gRPC AsyncIO backend transport for ImageVersions. - - Readonly service to query available ImageVersions. - - 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 = 'composer.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 = 'composer.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: 'composer.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] = {} - - 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 list_image_versions(self) -> Callable[ - [image_versions.ListImageVersionsRequest], - Awaitable[image_versions.ListImageVersionsResponse]]: - r"""Return a callable for the list image versions method over gRPC. - - List ImageVersions for provided location. - - Returns: - Callable[[~.ListImageVersionsRequest], - Awaitable[~.ListImageVersionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_image_versions' not in self._stubs: - self._stubs['list_image_versions'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1.ImageVersions/ListImageVersions', - request_serializer=image_versions.ListImageVersionsRequest.serialize, - response_deserializer=image_versions.ListImageVersionsResponse.deserialize, - ) - return self._stubs['list_image_versions'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_image_versions: self._wrap_method( - self.list_image_versions, - 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 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__ = ( - 'ImageVersionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest.py deleted file mode 100644 index e33feadced89..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest.py +++ /dev/null @@ -1,742 +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 requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.orchestration.airflow.service_v1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseImageVersionsRestTransport -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 ImageVersionsRestInterceptor: - """Interceptor for ImageVersions. - - 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 ImageVersionsRestTransport. - - .. code-block:: python - class MyCustomImageVersionsInterceptor(ImageVersionsRestInterceptor): - def pre_list_image_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_image_versions(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ImageVersionsRestTransport(interceptor=MyCustomImageVersionsInterceptor()) - client = ImageVersionsClient(transport=transport) - - - """ - def pre_list_image_versions(self, request: image_versions.ListImageVersionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_versions.ListImageVersionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_image_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the ImageVersions server. - """ - return request, metadata - - def post_list_image_versions(self, response: image_versions.ListImageVersionsResponse) -> image_versions.ListImageVersionsResponse: - """Post-rpc interceptor for list_image_versions - - DEPRECATED. Please use the `post_list_image_versions_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the ImageVersions server but before - it is returned to user code. This `post_list_image_versions` interceptor runs - before the `post_list_image_versions_with_metadata` interceptor. - """ - return response - - def post_list_image_versions_with_metadata(self, response: image_versions.ListImageVersionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_versions.ListImageVersionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_image_versions - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the ImageVersions server but before it is returned to user code. - - We recommend only using this `post_list_image_versions_with_metadata` - interceptor in new development instead of the `post_list_image_versions` interceptor. - When both interceptors are used, this `post_list_image_versions_with_metadata` interceptor runs after the - `post_list_image_versions` interceptor. The (possibly modified) response returned by - `post_list_image_versions` will be passed to - `post_list_image_versions_with_metadata`. - """ - return response, metadata - - 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ImageVersionsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ImageVersionsRestInterceptor - - -class ImageVersionsRestTransport(_BaseImageVersionsRestTransport): - """REST backend synchronous transport for ImageVersions. - - Readonly service to query available ImageVersions. - - 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 = 'composer.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[ImageVersionsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'composer.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) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ImageVersionsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ListImageVersions(_BaseImageVersionsRestTransport._BaseListImageVersions, ImageVersionsRestStub): - def __hash__(self): - return hash("ImageVersionsRestTransport.ListImageVersions") - - @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: image_versions.ListImageVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> image_versions.ListImageVersionsResponse: - r"""Call the list image versions method over HTTP. - - Args: - request (~.image_versions.ListImageVersionsRequest): - The request object. List ImageVersions in a project and - location. - retry (google.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: - ~.image_versions.ListImageVersionsResponse: - The ImageVersions in a project and - location. - - """ - - http_options = _BaseImageVersionsRestTransport._BaseListImageVersions._get_http_options() - - request, metadata = self._interceptor.pre_list_image_versions(request, metadata) - transcoded_request = _BaseImageVersionsRestTransport._BaseListImageVersions._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseImageVersionsRestTransport._BaseListImageVersions._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.orchestration.airflow.service_v1.ImageVersionsClient.ListImageVersions", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "rpcName": "ListImageVersions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ImageVersionsRestTransport._ListImageVersions._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 = image_versions.ListImageVersionsResponse() - pb_resp = image_versions.ListImageVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_image_versions(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_image_versions_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = image_versions.ListImageVersionsResponse.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.orchestration.airflow.service_v1.ImageVersionsClient.list_image_versions", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "rpcName": "ListImageVersions", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def list_image_versions(self) -> Callable[ - [image_versions.ListImageVersionsRequest], - image_versions.ListImageVersionsResponse]: - # 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._ListImageVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseImageVersionsRestTransport._BaseDeleteOperation, ImageVersionsRestStub): - def __hash__(self): - return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseDeleteOperation._get_http_options() - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseImageVersionsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1.ImageVersionsClient.DeleteOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ImageVersionsRestTransport._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(_BaseImageVersionsRestTransport._BaseGetOperation, ImageVersionsRestStub): - def __hash__(self): - return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseImageVersionsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1.ImageVersionsClient.GetOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ImageVersionsRestTransport._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.orchestration.airflow.service_v1.ImageVersionsAsyncClient.GetOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "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(_BaseImageVersionsRestTransport._BaseListOperations, ImageVersionsRestStub): - def __hash__(self): - return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseImageVersionsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1.ImageVersionsClient.ListOperations", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ImageVersionsRestTransport._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.orchestration.airflow.service_v1.ImageVersionsAsyncClient.ListOperations", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "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__=( - 'ImageVersionsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest_base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest_base.py deleted file mode 100644 index 4698fbffe626..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/transports/rest_base.py +++ /dev/null @@ -1,196 +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 ImageVersionsTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.orchestration.airflow.service_v1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseImageVersionsRestTransport(ImageVersionsTransport): - """Base REST backend transport for ImageVersions. - - 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 = 'composer.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: 'composer.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 _BaseListImageVersions: - 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/{parent=projects/*/locations/*}/imageVersions', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = image_versions.ListImageVersionsRequest.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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - 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__=( - '_BaseImageVersionsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py deleted file mode 100644 index 3105fb19469d..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py +++ /dev/null @@ -1,152 +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 .environments import ( - AirflowMetadataRetentionPolicyConfig, - CheckUpgradeRequest, - CheckUpgradeResponse, - CloudDataLineageIntegration, - CreateEnvironmentRequest, - CreateUserWorkloadsConfigMapRequest, - CreateUserWorkloadsSecretRequest, - DatabaseConfig, - DatabaseFailoverRequest, - DatabaseFailoverResponse, - DataRetentionConfig, - DeleteEnvironmentRequest, - DeleteUserWorkloadsConfigMapRequest, - DeleteUserWorkloadsSecretRequest, - EncryptionConfig, - Environment, - EnvironmentConfig, - ExecuteAirflowCommandRequest, - ExecuteAirflowCommandResponse, - FetchDatabasePropertiesRequest, - FetchDatabasePropertiesResponse, - GetEnvironmentRequest, - GetUserWorkloadsConfigMapRequest, - GetUserWorkloadsSecretRequest, - IPAllocationPolicy, - ListEnvironmentsRequest, - ListEnvironmentsResponse, - ListUserWorkloadsConfigMapsRequest, - ListUserWorkloadsConfigMapsResponse, - ListUserWorkloadsSecretsRequest, - ListUserWorkloadsSecretsResponse, - ListWorkloadsRequest, - ListWorkloadsResponse, - LoadSnapshotRequest, - LoadSnapshotResponse, - MaintenanceWindow, - MasterAuthorizedNetworksConfig, - NetworkingConfig, - NodeConfig, - PollAirflowCommandRequest, - PollAirflowCommandResponse, - PrivateClusterConfig, - PrivateEnvironmentConfig, - RecoveryConfig, - SaveSnapshotRequest, - SaveSnapshotResponse, - ScheduledSnapshotsConfig, - SoftwareConfig, - StopAirflowCommandRequest, - StopAirflowCommandResponse, - StorageConfig, - TaskLogsRetentionConfig, - UpdateEnvironmentRequest, - UpdateUserWorkloadsConfigMapRequest, - UpdateUserWorkloadsSecretRequest, - UserWorkloadsConfigMap, - UserWorkloadsSecret, - WebServerConfig, - WebServerNetworkAccessControl, - WorkloadsConfig, -) -from .image_versions import ( - ImageVersion, - ListImageVersionsRequest, - ListImageVersionsResponse, -) -from .operations import ( - OperationMetadata, -) - -__all__ = ( - 'AirflowMetadataRetentionPolicyConfig', - 'CheckUpgradeRequest', - 'CheckUpgradeResponse', - 'CloudDataLineageIntegration', - 'CreateEnvironmentRequest', - 'CreateUserWorkloadsConfigMapRequest', - 'CreateUserWorkloadsSecretRequest', - 'DatabaseConfig', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'DataRetentionConfig', - 'DeleteEnvironmentRequest', - 'DeleteUserWorkloadsConfigMapRequest', - 'DeleteUserWorkloadsSecretRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'GetEnvironmentRequest', - 'GetUserWorkloadsConfigMapRequest', - 'GetUserWorkloadsSecretRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'ListUserWorkloadsConfigMapsRequest', - 'ListUserWorkloadsConfigMapsResponse', - 'ListUserWorkloadsSecretsRequest', - 'ListUserWorkloadsSecretsResponse', - 'ListWorkloadsRequest', - 'ListWorkloadsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'StorageConfig', - 'TaskLogsRetentionConfig', - 'UpdateEnvironmentRequest', - 'UpdateUserWorkloadsConfigMapRequest', - 'UpdateUserWorkloadsSecretRequest', - 'UserWorkloadsConfigMap', - 'UserWorkloadsSecret', - 'WebServerConfig', - 'WebServerNetworkAccessControl', - 'WorkloadsConfig', - 'ImageVersion', - 'ListImageVersionsRequest', - 'ListImageVersionsResponse', - 'OperationMetadata', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py deleted file mode 100644 index 10b50b735f1e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py +++ /dev/null @@ -1,3089 +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 field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.orchestration.airflow.service.v1', - manifest={ - 'CreateEnvironmentRequest', - 'GetEnvironmentRequest', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'DeleteEnvironmentRequest', - 'UpdateEnvironmentRequest', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'CreateUserWorkloadsSecretRequest', - 'GetUserWorkloadsSecretRequest', - 'ListUserWorkloadsSecretsRequest', - 'UpdateUserWorkloadsSecretRequest', - 'DeleteUserWorkloadsSecretRequest', - 'CreateUserWorkloadsConfigMapRequest', - 'GetUserWorkloadsConfigMapRequest', - 'ListUserWorkloadsConfigMapsRequest', - 'UpdateUserWorkloadsConfigMapRequest', - 'DeleteUserWorkloadsConfigMapRequest', - 'UserWorkloadsSecret', - 'ListUserWorkloadsSecretsResponse', - 'UserWorkloadsConfigMap', - 'ListUserWorkloadsConfigMapsResponse', - 'ListWorkloadsRequest', - 'ListWorkloadsResponse', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'StorageConfig', - 'EnvironmentConfig', - 'WebServerNetworkAccessControl', - 'DatabaseConfig', - 'WebServerConfig', - 'EncryptionConfig', - 'MaintenanceWindow', - 'SoftwareConfig', - 'IPAllocationPolicy', - 'NodeConfig', - 'PrivateClusterConfig', - 'NetworkingConfig', - 'PrivateEnvironmentConfig', - 'WorkloadsConfig', - 'RecoveryConfig', - 'ScheduledSnapshotsConfig', - 'MasterAuthorizedNetworksConfig', - 'CloudDataLineageIntegration', - 'Environment', - 'CheckUpgradeRequest', - 'CheckUpgradeResponse', - 'DataRetentionConfig', - 'TaskLogsRetentionConfig', - 'AirflowMetadataRetentionPolicyConfig', - }, -) - - -class CreateEnvironmentRequest(proto.Message): - r"""Create a new environment. - - Attributes: - parent (str): - The parent must be of the form - "projects/{projectId}/locations/{locationId}". - environment (google.cloud.orchestration.airflow.service_v1.types.Environment): - The environment to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - environment: 'Environment' = proto.Field( - proto.MESSAGE, - number=2, - message='Environment', - ) - - -class GetEnvironmentRequest(proto.Message): - r"""Get an environment. - - Attributes: - name (str): - The resource name of the environment to get, - in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListEnvironmentsRequest(proto.Message): - r"""List environments in a project and location. - - Attributes: - parent (str): - List environments in the given project and - location, in the form: - "projects/{projectId}/locations/{locationId}". - page_size (int): - The maximum number of environments to return. - page_token (str): - The next_page_token value returned from a previous List - 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 ListEnvironmentsResponse(proto.Message): - r"""The environments in a project and location. - - Attributes: - environments (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.Environment]): - The list of environments returned by a - ListEnvironmentsRequest. - next_page_token (str): - The page token used to query for the next - page if one exists. - """ - - @property - def raw_page(self): - return self - - environments: MutableSequence['Environment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Environment', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteEnvironmentRequest(proto.Message): - r"""Delete an environment. - - Attributes: - name (str): - The environment to delete, in the form: - - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateEnvironmentRequest(proto.Message): - r"""Update an environment. - - Attributes: - name (str): - The relative resource name of the environment - to update, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - environment (google.cloud.orchestration.airflow.service_v1.types.Environment): - A patch environment. Fields specified by the ``updateMask`` - will be copied from the patch environment into the - environment under update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A comma-separated list of paths, relative to - ``Environment``, of fields to update. For example, to set - the version of scikit-learn to install in the environment to - 0.19.0 and to remove an existing installation of numpy, the - ``updateMask`` parameter would include the following two - ``paths`` values: - "config.softwareConfig.pypiPackages.scikit-learn" and - "config.softwareConfig.pypiPackages.numpy". The included - patch environment would specify the scikit-learn version as - follows: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "scikit-learn":"==0.19.0" - } - } - } - } - - Note that in the above example, any existing PyPI packages - other than scikit-learn and numpy will be unaffected. - - Only one update type may be included in a single request's - ``updateMask``. For example, one cannot update both the PyPI - packages and labels in the same request. However, it is - possible to update multiple members of a map field - simultaneously in the same request. For example, to set the - labels "label1" and "label2" while clearing "label3" - (assuming it already exists), one can provide the paths - "labels.label1", "labels.label2", and "labels.label3" and - populate the patch environment as follows: - - :: - - { - "labels":{ - "label1":"new-label1-value" - "label2":"new-label2-value" - } - } - - Note that in the above example, any existing labels that are - not included in the ``updateMask`` will be unaffected. - - It is also possible to replace an entire map field by - providing the map field's path in the ``updateMask``. The - new value of the field will be that which is provided in the - patch environment. For example, to delete all pre-existing - user-specified PyPI packages and install botocore at version - 1.7.14, the ``updateMask`` would contain the path - "config.softwareConfig.pypiPackages", and the patch - environment would be the following: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "botocore":"==1.7.14" - } - } - } - } - - **Note:** Only the following fields can be updated: - - - ``config.softwareConfig.pypiPackages`` - - - Replace all custom custom PyPI packages. If a - replacement package map is not included in - ``environment``, all custom PyPI packages are cleared. - It is an error to provide both this mask and a mask - specifying an individual package. - - - ``config.softwareConfig.pypiPackages.``\ packagename - - - Update the custom PyPI package *packagename*, - preserving other packages. To delete the package, - include it in ``updateMask``, and omit the mapping for - it in - ``environment.config.softwareConfig.pypiPackages``. It - is an error to provide both a mask of this form and - the ``config.softwareConfig.pypiPackages`` mask. - - - ``labels`` - - - Replace all environment labels. If a replacement - labels map is not included in ``environment``, all - labels are cleared. It is an error to provide both - this mask and a mask specifying one or more individual - labels. - - - ``labels.``\ labelName - - - Set the label named *labelName*, while preserving - other labels. To delete the label, include it in - ``updateMask`` and omit its mapping in - ``environment.labels``. It is an error to provide both - a mask of this form and the ``labels`` mask. - - - ``config.nodeCount`` - - - Horizontally scale the number of nodes in the - environment. An integer greater than or equal to 3 - must be provided in the ``config.nodeCount`` field. - Supported for Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerNetworkAccessControl`` - - - Replace the environment's current - ``WebServerNetworkAccessControl``. - - - ``config.softwareConfig.airflowConfigOverrides`` - - - Replace all Apache Airflow config overrides. If a - replacement config overrides map is not included in - ``environment``, all config overrides are cleared. It - is an error to provide both this mask and a mask - specifying one or more individual config overrides. - - - ``config.softwareConfig.airflowConfigOverrides.``\ section-name - - - Override the Apache Airflow config property *name* in - the section named *section*, preserving other - properties. To delete the property override, include - it in ``updateMask`` and omit its mapping in - ``environment.config.softwareConfig.airflowConfigOverrides``. - It is an error to provide both a mask of this form and - the ``config.softwareConfig.airflowConfigOverrides`` - mask. - - - ``config.softwareConfig.envVariables`` - - - Replace all environment variables. If a replacement - environment variable map is not included in - ``environment``, all custom environment variables are - cleared. - - - ``config.softwareConfig.schedulerCount`` - - - Horizontally scale the number of schedulers in - Airflow. A positive integer not greater than the - number of nodes must be provided in the - ``config.softwareConfig.schedulerCount`` field. - Supported for Cloud Composer environments in versions - composer-1.\ *.*-airflow-2.*.*. - - - ``config.databaseConfig.machineType`` - - - Cloud SQL machine type used by Airflow database. It - has to be one of: db-n1-standard-2, db-n1-standard-4, - db-n1-standard-8 or db-n1-standard-16. Supported for - Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerConfig.machineType`` - - - Machine type on which Airflow web server is running. - It has to be one of: composer-n1-webserver-2, - composer-n1-webserver-4 or composer-n1-webserver-8. - Supported for Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - """ - - name: str = proto.Field( - proto.STRING, - number=2, - ) - environment: 'Environment' = proto.Field( - proto.MESSAGE, - number=1, - message='Environment', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class ExecuteAirflowCommandRequest(proto.Message): - r"""Execute Airflow Command request. - - Attributes: - environment (str): - The resource name of the environment in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - command (str): - Airflow command. - subcommand (str): - Airflow subcommand. - parameters (MutableSequence[str]): - Parameters for the Airflow command/subcommand as an array of - arguments. It may contain positional arguments like - ``["my-dag-id"]``, key-value parameters like - ``["--foo=bar"]`` or ``["--foo","bar"]``, or other flags - like ``["-f"]``. - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - command: str = proto.Field( - proto.STRING, - number=2, - ) - subcommand: str = proto.Field( - proto.STRING, - number=3, - ) - parameters: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -class ExecuteAirflowCommandResponse(proto.Message): - r"""Response to ExecuteAirflowCommandRequest. - - Attributes: - execution_id (str): - The unique ID of the command execution for - polling. - pod (str): - The name of the pod where the command is - executed. - pod_namespace (str): - The namespace of the pod where the command is - executed. - error (str): - Error message. Empty if there was no error. - """ - - execution_id: str = proto.Field( - proto.STRING, - number=1, - ) - pod: str = proto.Field( - proto.STRING, - number=2, - ) - pod_namespace: str = proto.Field( - proto.STRING, - number=3, - ) - error: str = proto.Field( - proto.STRING, - number=4, - ) - - -class StopAirflowCommandRequest(proto.Message): - r"""Stop Airflow Command request. - - Attributes: - environment (str): - The resource name of the environment in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - execution_id (str): - The unique ID of the command execution. - pod (str): - The name of the pod where the command is - executed. - pod_namespace (str): - The namespace of the pod where the command is - executed. - force (bool): - If true, the execution is terminated - forcefully (SIGKILL). If false, the execution is - stopped gracefully, giving it time for cleanup. - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - execution_id: str = proto.Field( - proto.STRING, - number=2, - ) - pod: str = proto.Field( - proto.STRING, - number=3, - ) - pod_namespace: str = proto.Field( - proto.STRING, - number=4, - ) - force: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class StopAirflowCommandResponse(proto.Message): - r"""Response to StopAirflowCommandRequest. - - Attributes: - is_done (bool): - Whether the execution is still running. - output (MutableSequence[str]): - Output message from stopping execution - request. - """ - - is_done: bool = proto.Field( - proto.BOOL, - number=1, - ) - output: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class PollAirflowCommandRequest(proto.Message): - r"""Poll Airflow Command request. - - Attributes: - environment (str): - The resource name of the environment in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - execution_id (str): - The unique ID of the command execution. - pod (str): - The name of the pod where the command is - executed. - pod_namespace (str): - The namespace of the pod where the command is - executed. - next_line_number (int): - Line number from which new logs should be - fetched. - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - execution_id: str = proto.Field( - proto.STRING, - number=2, - ) - pod: str = proto.Field( - proto.STRING, - number=3, - ) - pod_namespace: str = proto.Field( - proto.STRING, - number=4, - ) - next_line_number: int = proto.Field( - proto.INT32, - number=5, - ) - - -class PollAirflowCommandResponse(proto.Message): - r"""Response to PollAirflowCommandRequest. - - Attributes: - output (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandResponse.Line]): - Output from the command execution. It may not - contain the full output and the caller may need - to poll for more lines. - output_end (bool): - Whether the command execution has finished - and there is no more output. - exit_info (google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandResponse.ExitInfo): - The result exit status of the command. - """ - - class Line(proto.Message): - r"""Contains information about a single line from logs. - - Attributes: - line_number (int): - Number of the line. - content (str): - Text content of the log line. - """ - - line_number: int = proto.Field( - proto.INT32, - number=1, - ) - content: str = proto.Field( - proto.STRING, - number=2, - ) - - class ExitInfo(proto.Message): - r"""Information about how a command ended. - - Attributes: - exit_code (int): - The exit code from the command execution. - error (str): - Error message. Empty if there was no error. - """ - - exit_code: int = proto.Field( - proto.INT32, - number=1, - ) - error: str = proto.Field( - proto.STRING, - number=2, - ) - - output: MutableSequence[Line] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Line, - ) - output_end: bool = proto.Field( - proto.BOOL, - number=2, - ) - exit_info: ExitInfo = proto.Field( - proto.MESSAGE, - number=3, - message=ExitInfo, - ) - - -class CreateUserWorkloadsSecretRequest(proto.Message): - r"""Create user workloads Secret request. - - Attributes: - parent (str): - Required. The environment name to create a - Secret for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - user_workloads_secret (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret): - Required. User workloads Secret to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_workloads_secret: 'UserWorkloadsSecret' = proto.Field( - proto.MESSAGE, - number=2, - message='UserWorkloadsSecret', - ) - - -class GetUserWorkloadsSecretRequest(proto.Message): - r"""Get user workloads Secret request. - - Attributes: - name (str): - Required. The resource name of the Secret to - get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListUserWorkloadsSecretsRequest(proto.Message): - r"""List user workloads Secrets request. - - Attributes: - parent (str): - Required. List Secrets in the given - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - page_size (int): - Optional. The maximum number of Secrets to - return. - page_token (str): - Optional. The next_page_token value returned from a previous - List 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 UpdateUserWorkloadsSecretRequest(proto.Message): - r"""Update user workloads Secret request. - - Attributes: - user_workloads_secret (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret): - Optional. User workloads Secret to override. - """ - - user_workloads_secret: 'UserWorkloadsSecret' = proto.Field( - proto.MESSAGE, - number=1, - message='UserWorkloadsSecret', - ) - - -class DeleteUserWorkloadsSecretRequest(proto.Message): - r"""Delete user workloads Secret request. - - Attributes: - name (str): - Required. The Secret to delete, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateUserWorkloadsConfigMapRequest(proto.Message): - r"""Create user workloads ConfigMap request. - - Attributes: - parent (str): - Required. The environment name to create a - ConfigMap for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - user_workloads_config_map (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap): - Required. User workloads ConfigMap to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_workloads_config_map: 'UserWorkloadsConfigMap' = proto.Field( - proto.MESSAGE, - number=2, - message='UserWorkloadsConfigMap', - ) - - -class GetUserWorkloadsConfigMapRequest(proto.Message): - r"""Get user workloads ConfigMap request. - - Attributes: - name (str): - Required. The resource name of the ConfigMap - to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListUserWorkloadsConfigMapsRequest(proto.Message): - r"""List user workloads ConfigMaps request. - - Attributes: - parent (str): - Required. List ConfigMaps in the given - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - page_size (int): - Optional. The maximum number of ConfigMaps to - return. - page_token (str): - Optional. The next_page_token value returned from a previous - List 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 UpdateUserWorkloadsConfigMapRequest(proto.Message): - r"""Update user workloads ConfigMap request. - - Attributes: - user_workloads_config_map (google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap): - Optional. User workloads ConfigMap to - override. - """ - - user_workloads_config_map: 'UserWorkloadsConfigMap' = proto.Field( - proto.MESSAGE, - number=1, - message='UserWorkloadsConfigMap', - ) - - -class DeleteUserWorkloadsConfigMapRequest(proto.Message): - r"""Delete user workloads ConfigMap request. - - Attributes: - name (str): - Required. The ConfigMap to delete, in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UserWorkloadsSecret(proto.Message): - r"""User workloads Secret used by Airflow tasks that run with - Kubernetes executor or KubernetesPodOperator. - - Attributes: - name (str): - Identifier. The resource name of the Secret, - in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". - data (MutableMapping[str, str]): - Optional. The "data" field of Kubernetes - Secret, organized in key-value pairs, which can - contain sensitive values such as a password, a - token, or a key. The values for all keys have to - be base64-encoded strings. For details see: - https://kubernetes.io/docs/concepts/configuration/secret/ - - Example: - - { - "example": "ZXhhbXBsZV92YWx1ZQ==", - "another-example": - "YW5vdGhlcl9leGFtcGxlX3ZhbHVl" } - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - data: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -class ListUserWorkloadsSecretsResponse(proto.Message): - r"""The user workloads Secrets for a given environment. - - Attributes: - user_workloads_secrets (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret]): - The list of Secrets returned by a - ListUserWorkloadsSecretsRequest. - next_page_token (str): - The page token used to query for the next - page if one exists. - """ - - @property - def raw_page(self): - return self - - user_workloads_secrets: MutableSequence['UserWorkloadsSecret'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='UserWorkloadsSecret', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UserWorkloadsConfigMap(proto.Message): - r"""User workloads ConfigMap used by Airflow tasks that run with - Kubernetes executor or KubernetesPodOperator. - - Attributes: - name (str): - Identifier. The resource name of the - ConfigMap, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". - data (MutableMapping[str, str]): - Optional. The "data" field of Kubernetes ConfigMap, - organized in key-value pairs. For details see: - https://kubernetes.io/docs/concepts/configuration/configmap/ - - Example: - - { "example_key": "example_value", "another_key": - "another_value" } - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - data: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -class ListUserWorkloadsConfigMapsResponse(proto.Message): - r"""The user workloads ConfigMaps for a given environment. - - Attributes: - user_workloads_config_maps (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap]): - The list of ConfigMaps returned by a - ListUserWorkloadsConfigMapsRequest. - next_page_token (str): - The page token used to query for the next - page if one exists. - """ - - @property - def raw_page(self): - return self - - user_workloads_config_maps: MutableSequence['UserWorkloadsConfigMap'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='UserWorkloadsConfigMap', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListWorkloadsRequest(proto.Message): - r"""Request for listing workloads in a Cloud Composer - environment. - - Attributes: - parent (str): - Required. The environment name to get - workloads for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - page_size (int): - Optional. The maximum number of environments - to return. - page_token (str): - Optional. The next_page_token value returned from a previous - List request, if any. - filter (str): - Optional. The list filter. Currently only supports equality - on the type field. The value of a field specified in the - filter expression must be one ComposerWorkloadType enum - option. It's possible to get multiple types using "OR" - operator, e.g.: "type=SCHEDULER OR type=CELERY_WORKER". If - not specified, all items are returned. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListWorkloadsResponse(proto.Message): - r"""Response to ListWorkloadsRequest. - - Attributes: - workloads (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse.ComposerWorkload]): - The list of environment workloads. - next_page_token (str): - The page token used to query for the next - page if one exists. - """ - class ComposerWorkloadType(proto.Enum): - r"""Supported workload types. - - Values: - COMPOSER_WORKLOAD_TYPE_UNSPECIFIED (0): - Not able to determine the type of the - workload. - CELERY_WORKER (1): - Celery worker. - KUBERNETES_WORKER (2): - Kubernetes worker. - KUBERNETES_OPERATOR_POD (3): - Workload created by Kubernetes Pod Operator. - SCHEDULER (4): - Airflow scheduler. - DAG_PROCESSOR (5): - Airflow Dag processor. - TRIGGERER (6): - Airflow triggerer. - WEB_SERVER (7): - Airflow web server UI. - REDIS (8): - Redis. - """ - COMPOSER_WORKLOAD_TYPE_UNSPECIFIED = 0 - CELERY_WORKER = 1 - KUBERNETES_WORKER = 2 - KUBERNETES_OPERATOR_POD = 3 - SCHEDULER = 4 - DAG_PROCESSOR = 5 - TRIGGERER = 6 - WEB_SERVER = 7 - REDIS = 8 - - class ComposerWorkloadState(proto.Enum): - r"""Workload states. - - Values: - COMPOSER_WORKLOAD_STATE_UNSPECIFIED (0): - Not able to determine the status of the - workload. - PENDING (1): - Workload is in pending state and has not yet - started. - OK (2): - Workload is running fine. - WARNING (3): - Workload is running but there are some - non-critical problems. - ERROR (4): - Workload is not running due to an error. - SUCCEEDED (5): - Workload has finished execution with success. - FAILED (6): - Workload has finished execution with failure. - """ - COMPOSER_WORKLOAD_STATE_UNSPECIFIED = 0 - PENDING = 1 - OK = 2 - WARNING = 3 - ERROR = 4 - SUCCEEDED = 5 - FAILED = 6 - - class ComposerWorkload(proto.Message): - r"""Information about a single workload. - - Attributes: - name (str): - Name of a workload. - type_ (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse.ComposerWorkloadType): - Type of a workload. - status (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse.ComposerWorkloadStatus): - Output only. Status of a workload. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'ListWorkloadsResponse.ComposerWorkloadType' = proto.Field( - proto.ENUM, - number=2, - enum='ListWorkloadsResponse.ComposerWorkloadType', - ) - status: 'ListWorkloadsResponse.ComposerWorkloadStatus' = proto.Field( - proto.MESSAGE, - number=3, - message='ListWorkloadsResponse.ComposerWorkloadStatus', - ) - - class ComposerWorkloadStatus(proto.Message): - r"""Workload status. - - Attributes: - state (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse.ComposerWorkloadState): - Output only. Workload state. - status_message (str): - Output only. Text to provide more descriptive - status. - detailed_status_message (str): - Output only. Detailed message of the status. - """ - - state: 'ListWorkloadsResponse.ComposerWorkloadState' = proto.Field( - proto.ENUM, - number=1, - enum='ListWorkloadsResponse.ComposerWorkloadState', - ) - status_message: str = proto.Field( - proto.STRING, - number=2, - ) - detailed_status_message: str = proto.Field( - proto.STRING, - number=3, - ) - - @property - def raw_page(self): - return self - - workloads: MutableSequence[ComposerWorkload] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ComposerWorkload, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SaveSnapshotRequest(proto.Message): - r"""Request to create a snapshot of a Cloud Composer environment. - - Attributes: - environment (str): - The resource name of the source environment - in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - snapshot_location (str): - Location in a Cloud Storage where the - snapshot is going to be stored, e.g.: - "gs://my-bucket/snapshots". - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - snapshot_location: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SaveSnapshotResponse(proto.Message): - r"""Response to SaveSnapshotRequest. - - Attributes: - snapshot_path (str): - The fully-resolved Cloud Storage path of the created - snapshot, e.g.: - "gs://my-bucket/snapshots/project_location_environment_timestamp". - This field is populated only if the snapshot creation was - successful. - """ - - snapshot_path: str = proto.Field( - proto.STRING, - number=1, - ) - - -class LoadSnapshotRequest(proto.Message): - r"""Request to load a snapshot into a Cloud Composer environment. - - Attributes: - environment (str): - The resource name of the target environment - in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - snapshot_path (str): - A Cloud Storage path to a snapshot to load, e.g.: - "gs://my-bucket/snapshots/project_location_environment_timestamp". - skip_pypi_packages_installation (bool): - Whether or not to skip installing Pypi - packages when loading the environment's state. - skip_environment_variables_setting (bool): - Whether or not to skip setting environment - variables when loading the environment's state. - skip_airflow_overrides_setting (bool): - Whether or not to skip setting Airflow - overrides when loading the environment's state. - skip_gcs_data_copying (bool): - Whether or not to skip copying Cloud Storage - data when loading the environment's state. - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - snapshot_path: str = proto.Field( - proto.STRING, - number=2, - ) - skip_pypi_packages_installation: bool = proto.Field( - proto.BOOL, - number=3, - ) - skip_environment_variables_setting: bool = proto.Field( - proto.BOOL, - number=4, - ) - skip_airflow_overrides_setting: bool = proto.Field( - proto.BOOL, - number=5, - ) - skip_gcs_data_copying: bool = proto.Field( - proto.BOOL, - number=6, - ) - - -class LoadSnapshotResponse(proto.Message): - r"""Response to LoadSnapshotRequest. - """ - - -class DatabaseFailoverRequest(proto.Message): - r"""Request to trigger database failover (only for highly - resilient environments). - - Attributes: - environment (str): - Target environment: - - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DatabaseFailoverResponse(proto.Message): - r"""Response for DatabaseFailoverRequest. - """ - - -class FetchDatabasePropertiesRequest(proto.Message): - r"""Request to fetch properties of environment's database. - - Attributes: - environment (str): - Required. The resource name of the - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - - -class FetchDatabasePropertiesResponse(proto.Message): - r"""Response for FetchDatabasePropertiesRequest. - - Attributes: - primary_gce_zone (str): - The Compute Engine zone that the instance is - currently serving from. - secondary_gce_zone (str): - The Compute Engine zone that the failover - instance is currently serving from for a - regional Cloud SQL instance. - is_failover_replica_available (bool): - The availability status of the failover - replica. A false status indicates that the - failover replica is out of sync. The primary - instance can only fail over to the failover - replica when the status is true. - """ - - primary_gce_zone: str = proto.Field( - proto.STRING, - number=1, - ) - secondary_gce_zone: str = proto.Field( - proto.STRING, - number=2, - ) - is_failover_replica_available: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class StorageConfig(proto.Message): - r"""The configuration for data storage in the environment. - - Attributes: - bucket (str): - Optional. The name of the Cloud Storage bucket used by the - environment. No ``gs://`` prefix. - """ - - bucket: str = proto.Field( - proto.STRING, - number=1, - ) - - -class EnvironmentConfig(proto.Message): - r"""Configuration information for an environment. - - Attributes: - gke_cluster (str): - Output only. The Kubernetes Engine cluster - used to run this environment. - dag_gcs_prefix (str): - Output only. The Cloud Storage prefix of the - DAGs for this environment. Although Cloud - Storage objects reside in a flat namespace, a - hierarchical file tree can be simulated using - "/"-delimited object name prefixes. DAG objects - for this environment reside in a simulated - directory with the given prefix. - node_count (int): - The number of nodes in the Kubernetes Engine cluster that - will be used to run this environment. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - software_config (google.cloud.orchestration.airflow.service_v1.types.SoftwareConfig): - Optional. The configuration settings for - software inside the environment. - node_config (google.cloud.orchestration.airflow.service_v1.types.NodeConfig): - Optional. The configuration used for the - Kubernetes Engine cluster. - private_environment_config (google.cloud.orchestration.airflow.service_v1.types.PrivateEnvironmentConfig): - Optional. The configuration used for the - Private IP Cloud Composer environment. - web_server_network_access_control (google.cloud.orchestration.airflow.service_v1.types.WebServerNetworkAccessControl): - Optional. The network-level access control - policy for the Airflow web server. If - unspecified, no network-level access - restrictions will be applied. - database_config (google.cloud.orchestration.airflow.service_v1.types.DatabaseConfig): - Optional. The configuration settings for - Cloud SQL instance used internally by Apache - Airflow software. - web_server_config (google.cloud.orchestration.airflow.service_v1.types.WebServerConfig): - Optional. The configuration settings for the - Airflow web server App Engine instance. - encryption_config (google.cloud.orchestration.airflow.service_v1.types.EncryptionConfig): - Optional. The encryption options for the - Cloud Composer environment and its dependencies. - Cannot be updated. - maintenance_window (google.cloud.orchestration.airflow.service_v1.types.MaintenanceWindow): - Optional. The maintenance window is the - period when Cloud Composer components may - undergo maintenance. It is defined so that - maintenance is not executed during peak hours or - critical time periods. - - The system will not be under maintenance for - every occurrence of this window, but when - maintenance is planned, it will be scheduled - during the window. - - The maintenance window period must encompass at - least 12 hours per week. This may be split into - multiple chunks, each with a size of at least 4 - hours. - - If this value is omitted, the default value for - maintenance window is applied. By default, - maintenance windows are from 00:00:00 to - 04:00:00 (GMT) on Friday, Saturday, and Sunday - every week. - workloads_config (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig): - Optional. The workloads configuration settings for the GKE - cluster associated with the Cloud Composer environment. The - GKE cluster runs Airflow scheduler, web server and workers - workloads. - - This field is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - environment_size (google.cloud.orchestration.airflow.service_v1.types.EnvironmentConfig.EnvironmentSize): - Optional. The size of the Cloud Composer environment. - - This field is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - airflow_uri (str): - Output only. The URI of the Apache Airflow Web UI hosted - within this environment (see `Airflow web - interface `__). - airflow_byoid_uri (str): - Output only. The 'bring your own identity' variant of the - URI of the Apache Airflow Web UI hosted within this - environment, to be accessed with external identities using - workforce identity federation (see `Access environments with - workforce identity - federation `__). - master_authorized_networks_config (google.cloud.orchestration.airflow.service_v1.types.MasterAuthorizedNetworksConfig): - Optional. The configuration options for GKE - cluster master authorized networks. By default - master authorized networks feature is: - - - in case of private environment: enabled with - no external networks allowlisted. - - in case of public environment: disabled. - recovery_config (google.cloud.orchestration.airflow.service_v1.types.RecoveryConfig): - Optional. The Recovery settings configuration of an - environment. - - This field is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - resilience_mode (google.cloud.orchestration.airflow.service_v1.types.EnvironmentConfig.ResilienceMode): - Optional. Resilience mode of the Cloud Composer Environment. - - This field is supported for Cloud Composer environments in - versions composer-2.2.0-airflow-\ *.*.\* and newer. - data_retention_config (google.cloud.orchestration.airflow.service_v1.types.DataRetentionConfig): - Optional. The configuration setting for - Airflow database data retention mechanism. - """ - class EnvironmentSize(proto.Enum): - r"""The size of the Cloud Composer environment. - - Values: - ENVIRONMENT_SIZE_UNSPECIFIED (0): - The size of the environment is unspecified. - ENVIRONMENT_SIZE_SMALL (1): - The environment size is small. - ENVIRONMENT_SIZE_MEDIUM (2): - The environment size is medium. - ENVIRONMENT_SIZE_LARGE (3): - The environment size is large. - """ - ENVIRONMENT_SIZE_UNSPECIFIED = 0 - ENVIRONMENT_SIZE_SMALL = 1 - ENVIRONMENT_SIZE_MEDIUM = 2 - ENVIRONMENT_SIZE_LARGE = 3 - - class ResilienceMode(proto.Enum): - r"""Resilience mode of the Cloud Composer Environment. - - Values: - RESILIENCE_MODE_UNSPECIFIED (0): - Default mode doesn't change environment - parameters. - HIGH_RESILIENCE (1): - Enabled High Resilience mode, including Cloud - SQL HA. - """ - RESILIENCE_MODE_UNSPECIFIED = 0 - HIGH_RESILIENCE = 1 - - gke_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - dag_gcs_prefix: str = proto.Field( - proto.STRING, - number=2, - ) - node_count: int = proto.Field( - proto.INT32, - number=3, - ) - software_config: 'SoftwareConfig' = proto.Field( - proto.MESSAGE, - number=4, - message='SoftwareConfig', - ) - node_config: 'NodeConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='NodeConfig', - ) - private_environment_config: 'PrivateEnvironmentConfig' = proto.Field( - proto.MESSAGE, - number=7, - message='PrivateEnvironmentConfig', - ) - web_server_network_access_control: 'WebServerNetworkAccessControl' = proto.Field( - proto.MESSAGE, - number=8, - message='WebServerNetworkAccessControl', - ) - database_config: 'DatabaseConfig' = proto.Field( - proto.MESSAGE, - number=9, - message='DatabaseConfig', - ) - web_server_config: 'WebServerConfig' = proto.Field( - proto.MESSAGE, - number=10, - message='WebServerConfig', - ) - encryption_config: 'EncryptionConfig' = proto.Field( - proto.MESSAGE, - number=11, - message='EncryptionConfig', - ) - maintenance_window: 'MaintenanceWindow' = proto.Field( - proto.MESSAGE, - number=12, - message='MaintenanceWindow', - ) - workloads_config: 'WorkloadsConfig' = proto.Field( - proto.MESSAGE, - number=15, - message='WorkloadsConfig', - ) - environment_size: EnvironmentSize = proto.Field( - proto.ENUM, - number=16, - enum=EnvironmentSize, - ) - airflow_uri: str = proto.Field( - proto.STRING, - number=6, - ) - airflow_byoid_uri: str = proto.Field( - proto.STRING, - number=20, - ) - master_authorized_networks_config: 'MasterAuthorizedNetworksConfig' = proto.Field( - proto.MESSAGE, - number=17, - message='MasterAuthorizedNetworksConfig', - ) - recovery_config: 'RecoveryConfig' = proto.Field( - proto.MESSAGE, - number=18, - message='RecoveryConfig', - ) - resilience_mode: ResilienceMode = proto.Field( - proto.ENUM, - number=19, - enum=ResilienceMode, - ) - data_retention_config: 'DataRetentionConfig' = proto.Field( - proto.MESSAGE, - number=21, - message='DataRetentionConfig', - ) - - -class WebServerNetworkAccessControl(proto.Message): - r"""Network-level access control policy for the Airflow web - server. - - Attributes: - allowed_ip_ranges (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.WebServerNetworkAccessControl.AllowedIpRange]): - A collection of allowed IP ranges with - descriptions. - """ - - class AllowedIpRange(proto.Message): - r"""Allowed IP range with user-provided description. - - Attributes: - value (str): - IP address or range, defined using CIDR notation, of - requests that this rule applies to. Examples: - ``192.168.1.1`` or ``192.168.0.0/16`` or ``2001:db8::/32`` - or ``2001:0db8:0000:0042:0000:8a2e:0370:7334``. - - IP range prefixes should be properly truncated. For example, - ``1.2.3.4/24`` should be truncated to ``1.2.3.0/24``. - Similarly, for IPv6, ``2001:db8::1/32`` should be truncated - to ``2001:db8::/32``. - description (str): - Optional. User-provided description. It must - contain at most 300 characters. - """ - - value: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - - allowed_ip_ranges: MutableSequence[AllowedIpRange] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=AllowedIpRange, - ) - - -class DatabaseConfig(proto.Message): - r"""The configuration of Cloud SQL instance that is used by the - Apache Airflow software. - - Attributes: - machine_type (str): - Optional. Cloud SQL machine type used by Airflow database. - It has to be one of: db-n1-standard-2, db-n1-standard-4, - db-n1-standard-8 or db-n1-standard-16. If not specified, - db-n1-standard-2 will be used. Supported for Cloud Composer - environments in versions composer-1.\ *.*-airflow-*.*.*. - zone (str): - Optional. The Compute Engine zone where the Airflow database - is created. If zone is provided, it must be in the region - selected for the environment. If zone is not provided, a - zone is automatically selected. The zone can only be set - during environment creation. Supported for Cloud Composer - environments in versions composer-2.\ *.*-airflow-*.*.*. - """ - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - zone: str = proto.Field( - proto.STRING, - number=2, - ) - - -class WebServerConfig(proto.Message): - r"""The configuration settings for the Airflow web server App Engine - instance. Supported for Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.\* - - Attributes: - machine_type (str): - Optional. Machine type on which Airflow web - server is running. It has to be one of: - composer-n1-webserver-2, composer-n1-webserver-4 - or composer-n1-webserver-8. - If not specified, composer-n1-webserver-2 will - be used. Value custom is returned only in - response, if Airflow web server parameters were - manually changed to a non-standard values. - """ - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - - -class EncryptionConfig(proto.Message): - r"""The encryption options for the Cloud Composer environment and its - dependencies.Supported for Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - Attributes: - kms_key_name (str): - Optional. Customer-managed Encryption Key - available through Google's Key Management - Service. Cannot be updated. If not specified, - Google-managed key will be used. - """ - - kms_key_name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class MaintenanceWindow(proto.Message): - r"""The configuration settings for Cloud Composer maintenance window. - The following example: - - :: - - { - "startTime":"2019-08-01T01:00:00Z" - "endTime":"2019-08-01T07:00:00Z" - "recurrence":"FREQ=WEEKLY;BYDAY=TU,WE" - } - - would define a maintenance window between 01 and 07 hours UTC during - each Tuesday and Wednesday. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Start time of the first recurrence - of the maintenance window. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Maintenance window end time. It is used only to - calculate the duration of the maintenance window. The value - for end-time must be in the future, relative to - ``start_time``. - recurrence (str): - Required. Maintenance window recurrence. Format is a subset - of `RFC-5545 `__ - ``RRULE``. The only allowed values for ``FREQ`` field are - ``FREQ=DAILY`` and ``FREQ=WEEKLY;BYDAY=...`` Example values: - ``FREQ=WEEKLY;BYDAY=TU,WE``, ``FREQ=DAILY``. - """ - - start_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, - ) - recurrence: str = proto.Field( - proto.STRING, - number=3, - ) - - -class SoftwareConfig(proto.Message): - r"""Specifies the selection and configuration of software inside - the environment. - - Attributes: - image_version (str): - Optional. The version of the software running in the - environment. This encapsulates both the version of Cloud - Composer functionality and the version of Apache Airflow. It - must match the regular expression - ``composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)``. - When used as input, the server also checks if the provided - version is supported and denies the request for an - unsupported version. - - The Cloud Composer portion of the image version is a full - `semantic version `__, or an alias in - the form of major version number or ``latest``. When an - alias is provided, the server replaces it with the current - Cloud Composer version that satisfies the alias. - - The Apache Airflow portion of the image version is a full - semantic version that points to one of the supported Apache - Airflow versions, or an alias in the form of only major or - major.minor versions specified. When an alias is provided, - the server replaces it with the latest Apache Airflow - version that satisfies the alias and is supported in the - given Cloud Composer version. - - In all cases, the resolved image version is stored in the - same field. - - See also `version - list `__ - and `versioning - overview `__. - airflow_config_overrides (MutableMapping[str, str]): - Optional. Apache Airflow configuration properties to - override. - - Property keys contain the section and property names, - separated by a hyphen, for example - "core-dags_are_paused_at_creation". Section names must not - contain hyphens ("-"), opening square brackets ("["), or - closing square brackets ("]"). The property name must not be - empty and must not contain an equals sign ("=") or semicolon - (";"). Section and property names must not contain a period - ("."). Apache Airflow configuration property names must be - written in - `snake_case `__. - Property values can contain any character, and can be - written in any lower/upper case format. - - Certain Apache Airflow configuration property values are - `blocked `__, - and cannot be overridden. - pypi_packages (MutableMapping[str, str]): - Optional. Custom Python Package Index (PyPI) packages to be - installed in the environment. - - Keys refer to the lowercase package name such as "numpy" and - values are the lowercase extras and version specifier such - as "==1.12.0", "[devel,gcp_api]", or "[devel]>=1.8.2, - <1.9.2". To specify a package without pinning it to a - version specifier, use the empty string as the value. - env_variables (MutableMapping[str, str]): - Optional. Additional environment variables to provide to the - Apache Airflow scheduler, worker, and webserver processes. - - Environment variable names must match the regular expression - ``[a-zA-Z_][a-zA-Z0-9_]*``. They cannot specify Apache - Airflow software configuration overrides (they cannot match - the regular expression ``AIRFLOW__[A-Z0-9_]+__[A-Z0-9_]+``), - and they cannot match any of the following reserved names: - - - ``AIRFLOW_HOME`` - - ``C_FORCE_ROOT`` - - ``CONTAINER_NAME`` - - ``DAGS_FOLDER`` - - ``GCP_PROJECT`` - - ``GCS_BUCKET`` - - ``GKE_CLUSTER_NAME`` - - ``SQL_DATABASE`` - - ``SQL_INSTANCE`` - - ``SQL_PASSWORD`` - - ``SQL_PROJECT`` - - ``SQL_REGION`` - - ``SQL_USER`` - python_version (str): - Optional. The major version of Python used to run the Apache - Airflow scheduler, worker, and webserver processes. - - Can be set to '2' or '3'. If not specified, the default is - '3'. Cannot be updated. - - This field is only supported for Cloud Composer environments - in versions composer-1.\ *.*-airflow-*.*.*. Environments in - newer versions always use Python major version 3. - scheduler_count (int): - Optional. The number of schedulers for Airflow. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-2.*.*. - cloud_data_lineage_integration (google.cloud.orchestration.airflow.service_v1.types.CloudDataLineageIntegration): - Optional. The configuration for Cloud Data - Lineage integration. - web_server_plugins_mode (google.cloud.orchestration.airflow.service_v1.types.SoftwareConfig.WebServerPluginsMode): - Optional. Whether or not the web server uses custom plugins. - If unspecified, the field defaults to ``PLUGINS_ENABLED``. - - This field is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - """ - class WebServerPluginsMode(proto.Enum): - r"""Web server plugins mode of the Cloud Composer environment. - - Values: - WEB_SERVER_PLUGINS_MODE_UNSPECIFIED (0): - Default mode. - PLUGINS_DISABLED (1): - Web server plugins are not supported. - PLUGINS_ENABLED (2): - Web server plugins are supported. - """ - WEB_SERVER_PLUGINS_MODE_UNSPECIFIED = 0 - PLUGINS_DISABLED = 1 - PLUGINS_ENABLED = 2 - - image_version: str = proto.Field( - proto.STRING, - number=1, - ) - airflow_config_overrides: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - pypi_packages: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - env_variables: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - python_version: str = proto.Field( - proto.STRING, - number=6, - ) - scheduler_count: int = proto.Field( - proto.INT32, - number=7, - ) - cloud_data_lineage_integration: 'CloudDataLineageIntegration' = proto.Field( - proto.MESSAGE, - number=8, - message='CloudDataLineageIntegration', - ) - web_server_plugins_mode: WebServerPluginsMode = proto.Field( - proto.ENUM, - number=10, - enum=WebServerPluginsMode, - ) - - -class IPAllocationPolicy(proto.Message): - r"""Configuration for controlling how IPs are allocated in the - GKE cluster running the Apache Airflow software. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - use_ip_aliases (bool): - Optional. Whether or not to enable Alias IPs in the GKE - cluster. If ``true``, a VPC-native cluster is created. - - This field is only supported for Cloud Composer environments - in versions composer-1.\ *.*-airflow-*.*.*. Environments in - newer versions always use VPC-native GKE clusters. - cluster_secondary_range_name (str): - Optional. The name of the GKE cluster's secondary range used - to allocate IP addresses to pods. - - For Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*, this field is applicable - only when ``use_ip_aliases`` is true. - - This field is a member of `oneof`_ ``cluster_ip_allocation``. - cluster_ipv4_cidr_block (str): - Optional. The IP address range used to allocate IP addresses - to pods in the GKE cluster. - - For Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*, this field is applicable - only when ``use_ip_aliases`` is true. - - Set to blank to have GKE choose a range with the default - size. - - Set to /netmask (e.g. ``/14``) to have GKE choose a range - with a specific netmask. - - Set to a - `CIDR `__ - notation (e.g. ``10.96.0.0/14``) from the RFC-1918 private - networks (e.g. ``10.0.0.0/8``, ``172.16.0.0/12``, - ``192.168.0.0/16``) to pick a specific range to use. - - This field is a member of `oneof`_ ``cluster_ip_allocation``. - services_secondary_range_name (str): - Optional. The name of the services' secondary range used to - allocate IP addresses to the GKE cluster. - - For Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*, this field is applicable - only when ``use_ip_aliases`` is true. - - This field is a member of `oneof`_ ``services_ip_allocation``. - services_ipv4_cidr_block (str): - Optional. The IP address range of the services IP addresses - in this GKE cluster. - - For Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*, this field is applicable - only when ``use_ip_aliases`` is true. - - Set to blank to have GKE choose a range with the default - size. - - Set to /netmask (e.g. ``/14``) to have GKE choose a range - with a specific netmask. - - Set to a - `CIDR `__ - notation (e.g. ``10.96.0.0/14``) from the RFC-1918 private - networks (e.g. ``10.0.0.0/8``, ``172.16.0.0/12``, - ``192.168.0.0/16``) to pick a specific range to use. - - This field is a member of `oneof`_ ``services_ip_allocation``. - """ - - use_ip_aliases: bool = proto.Field( - proto.BOOL, - number=1, - ) - cluster_secondary_range_name: str = proto.Field( - proto.STRING, - number=2, - oneof='cluster_ip_allocation', - ) - cluster_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=4, - oneof='cluster_ip_allocation', - ) - services_secondary_range_name: str = proto.Field( - proto.STRING, - number=3, - oneof='services_ip_allocation', - ) - services_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=5, - oneof='services_ip_allocation', - ) - - -class NodeConfig(proto.Message): - r"""The configuration information for the Kubernetes Engine nodes - running the Apache Airflow software. - - Attributes: - location (str): - Optional. The Compute Engine - `zone `__ in which to deploy - the VMs used to run the Apache Airflow software, specified - as a `relative resource - name `__. - For example: "projects/{projectId}/zones/{zoneId}". - - This ``location`` must belong to the enclosing environment's - project and location. If both this field and - ``nodeConfig.machineType`` are specified, - ``nodeConfig.machineType`` must belong to this ``location``; - if both are unspecified, the service will pick a zone in the - Compute Engine region corresponding to the Cloud Composer - location, and propagate that choice to both fields. If only - one field (``location`` or ``nodeConfig.machineType``) is - specified, the location information from the specified field - will be propagated to the unspecified field. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - machine_type (str): - Optional. The Compute Engine `machine - type `__ used for cluster - instances, specified as a `relative resource - name `__. - For example: - "projects/{projectId}/zones/{zoneId}/machineTypes/{machineTypeId}". - - The ``machineType`` must belong to the enclosing - environment's project and location. If both this field and - ``nodeConfig.location`` are specified, this ``machineType`` - must belong to the ``nodeConfig.location``; if both are - unspecified, the service will pick a zone in the Compute - Engine region corresponding to the Cloud Composer location, - and propagate that choice to both fields. If exactly one of - this field and ``nodeConfig.location`` is specified, the - location information from the specified field will be - propagated to the unspecified field. - - The ``machineTypeId`` must not be a `shared-core machine - type `__. - - If this field is unspecified, the ``machineTypeId`` defaults - to "n1-standard-1". - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - network (str): - Optional. The Compute Engine network to be used for machine - communications, specified as a `relative resource - name `__. - For example: - "projects/{projectId}/global/networks/{networkId}". - - If unspecified, the "default" network ID in the - environment's project is used. If a `Custom Subnet - Network `__ is - provided, ``nodeConfig.subnetwork`` must also be provided. - For `Shared VPC `__ subnetwork - requirements, see ``nodeConfig.subnetwork``. - subnetwork (str): - Optional. The Compute Engine subnetwork to be used for - machine communications, specified as a `relative resource - name `__. - For example: - "projects/{projectId}/regions/{regionId}/subnetworks/{subnetworkId}" - - If a subnetwork is provided, ``nodeConfig.network`` must - also be provided, and the subnetwork must belong to the - enclosing environment's project and location. - disk_size_gb (int): - Optional. The disk size in GB used for node VMs. Minimum - size is 30GB. If unspecified, defaults to 100GB. Cannot be - updated. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - oauth_scopes (MutableSequence[str]): - Optional. The set of Google API scopes to be made available - on all node VMs. If ``oauth_scopes`` is empty, defaults to - ["https://www.googleapis.com/auth/cloud-platform"]. Cannot - be updated. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - service_account (str): - Optional. The Google Cloud Platform Service - Account to be used by the node VMs. If a service - account is not specified, the "default" Compute - Engine service account is used. Cannot be - updated. - tags (MutableSequence[str]): - Optional. The list of instance tags applied to all node VMs. - Tags are used to identify valid sources or targets for - network firewalls. Each tag within the list must comply with - `RFC1035 `__. Cannot - be updated. - ip_allocation_policy (google.cloud.orchestration.airflow.service_v1.types.IPAllocationPolicy): - Optional. The configuration for controlling - how IPs are allocated in the GKE cluster. - enable_ip_masq_agent (bool): - Optional. Deploys 'ip-masq-agent' daemon set - in the GKE cluster and defines - nonMasqueradeCIDRs equals to pod IP range so IP - masquerading is used for all destination - addresses, except between pods traffic. - - See: - - https://cloud.google.com/kubernetes-engine/docs/how-to/ip-masquerade-agent - composer_network_attachment (str): - Optional. Network Attachment that Cloud Composer environment - is connected to, which provides connectivity with a user's - VPC network. Takes precedence over network and subnetwork - settings. If not provided, but network and subnetwork are - defined during environment, it will be provisioned. If not - provided and network and subnetwork are also empty, then - connectivity to user's VPC network is disabled. Network - attachment must be provided in format - projects/{project}/regions/{region}/networkAttachments/{networkAttachment}. - - This field is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - composer_internal_ipv4_cidr_block (str): - Optional. The IP range in CIDR notation to use internally by - Cloud Composer. IP addresses are not reserved - and the same - range can be used by multiple Cloud Composer environments. - In case of overlap, IPs from this range will not be - accessible in the user's VPC network. Cannot be updated. If - not specified, the default value of '100.64.128.0/20' is - used. - - This field is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - """ - - location: str = proto.Field( - proto.STRING, - number=1, - ) - machine_type: str = proto.Field( - proto.STRING, - number=2, - ) - network: str = proto.Field( - proto.STRING, - number=3, - ) - subnetwork: str = proto.Field( - proto.STRING, - number=4, - ) - disk_size_gb: int = proto.Field( - proto.INT32, - number=5, - ) - oauth_scopes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - service_account: str = proto.Field( - proto.STRING, - number=7, - ) - tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - ip_allocation_policy: 'IPAllocationPolicy' = proto.Field( - proto.MESSAGE, - number=9, - message='IPAllocationPolicy', - ) - enable_ip_masq_agent: bool = proto.Field( - proto.BOOL, - number=11, - ) - composer_network_attachment: str = proto.Field( - proto.STRING, - number=12, - ) - composer_internal_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=13, - ) - - -class PrivateClusterConfig(proto.Message): - r"""Configuration options for the private GKE cluster in a Cloud - Composer environment. - - Attributes: - enable_private_endpoint (bool): - Optional. If ``true``, access to the public endpoint of the - GKE cluster is denied. - master_ipv4_cidr_block (str): - Optional. The CIDR block from which IPv4 - range for GKE master will be reserved. If left - blank, the default value of '172.16.0.0/23' is - used. - master_ipv4_reserved_range (str): - Output only. The IP range in CIDR notation to - use for the hosted master network. This range is - used for assigning internal IP addresses to the - GKE cluster master or set of masters and to the - internal load balancer virtual IP. This range - must not overlap with any other ranges in use - within the cluster's network. - """ - - enable_private_endpoint: bool = proto.Field( - proto.BOOL, - number=1, - ) - master_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=2, - ) - master_ipv4_reserved_range: str = proto.Field( - proto.STRING, - number=3, - ) - - -class NetworkingConfig(proto.Message): - r"""Configuration options for networking connections in the - Composer 2 environment. - - Attributes: - connection_type (google.cloud.orchestration.airflow.service_v1.types.NetworkingConfig.ConnectionType): - Optional. Indicates the user requested - specifc connection type between Tenant and - Customer projects. You cannot set networking - connection type in public IP environment. - """ - class ConnectionType(proto.Enum): - r"""Represents connection type between Composer environment in - Customer Project and the corresponding Tenant project, from a - predefined list of available connection modes. - - Values: - CONNECTION_TYPE_UNSPECIFIED (0): - No specific connection type was requested, so - the environment uses the default value - corresponding to the rest of its configuration. - VPC_PEERING (1): - Requests the use of VPC peerings for - connecting the Customer and Tenant projects. - PRIVATE_SERVICE_CONNECT (2): - Requests the use of Private Service Connect - for connecting the Customer and Tenant projects. - """ - CONNECTION_TYPE_UNSPECIFIED = 0 - VPC_PEERING = 1 - PRIVATE_SERVICE_CONNECT = 2 - - connection_type: ConnectionType = proto.Field( - proto.ENUM, - number=1, - enum=ConnectionType, - ) - - -class PrivateEnvironmentConfig(proto.Message): - r"""The configuration information for configuring a Private IP - Cloud Composer environment. - - Attributes: - enable_private_environment (bool): - Optional. If ``true``, a Private IP Cloud Composer - environment is created. If this field is set to true, - ``IPAllocationPolicy.use_ip_aliases`` must be set to true - for Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - enable_private_builds_only (bool): - Optional. If ``true``, builds performed during operations - that install Python packages have only private connectivity - to Google services (including Artifact Registry) and VPC - network (if either ``NodeConfig.network`` and - ``NodeConfig.subnetwork`` fields or - ``NodeConfig.composer_network_attachment`` field are - specified). If ``false``, the builds also have access to the - internet. - - This field is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - private_cluster_config (google.cloud.orchestration.airflow.service_v1.types.PrivateClusterConfig): - Optional. Configuration for the private GKE - cluster for a Private IP Cloud Composer - environment. - web_server_ipv4_cidr_block (str): - Optional. The CIDR block from which IP range for web server - will be reserved. Needs to be disjoint from - ``private_cluster_config.master_ipv4_cidr_block`` and - ``cloud_sql_ipv4_cidr_block``. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - cloud_sql_ipv4_cidr_block (str): - Optional. The CIDR block from which IP range in tenant - project will be reserved for Cloud SQL. Needs to be disjoint - from ``web_server_ipv4_cidr_block``. - web_server_ipv4_reserved_range (str): - Output only. The IP range reserved for the tenant project's - App Engine VMs. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - cloud_composer_network_ipv4_cidr_block (str): - Optional. The CIDR block from which IP range for Cloud - Composer Network in tenant project will be reserved. Needs - to be disjoint from - private_cluster_config.master_ipv4_cidr_block and - cloud_sql_ipv4_cidr_block. - - This field is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - cloud_composer_network_ipv4_reserved_range (str): - Output only. The IP range reserved for the tenant project's - Cloud Composer network. - - This field is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - enable_privately_used_public_ips (bool): - Optional. When enabled, IPs from public (non-RFC1918) ranges - can be used for - ``IPAllocationPolicy.cluster_ipv4_cidr_block`` and - ``IPAllocationPolicy.service_ipv4_cidr_block``. - cloud_composer_connection_subnetwork (str): - Optional. When specified, the environment - will use Private Service Connect instead of VPC - peerings to connect to Cloud SQL in the Tenant - Project, and the PSC endpoint in the Customer - Project will use an IP address from this - subnetwork. - networking_config (google.cloud.orchestration.airflow.service_v1.types.NetworkingConfig): - Optional. Configuration for the network - connections configuration in the environment. - """ - - enable_private_environment: bool = proto.Field( - proto.BOOL, - number=1, - ) - enable_private_builds_only: bool = proto.Field( - proto.BOOL, - number=11, - ) - private_cluster_config: 'PrivateClusterConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='PrivateClusterConfig', - ) - web_server_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=3, - ) - cloud_sql_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=4, - ) - web_server_ipv4_reserved_range: str = proto.Field( - proto.STRING, - number=5, - ) - cloud_composer_network_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=7, - ) - cloud_composer_network_ipv4_reserved_range: str = proto.Field( - proto.STRING, - number=8, - ) - enable_privately_used_public_ips: bool = proto.Field( - proto.BOOL, - number=6, - ) - cloud_composer_connection_subnetwork: str = proto.Field( - proto.STRING, - number=9, - ) - networking_config: 'NetworkingConfig' = proto.Field( - proto.MESSAGE, - number=10, - message='NetworkingConfig', - ) - - -class WorkloadsConfig(proto.Message): - r"""The Kubernetes workloads configuration for GKE cluster associated - with the Cloud Composer environment. Supported for Cloud Composer - environments in versions composer-2.\ *.*-airflow-*.*.\* and newer. - - Attributes: - scheduler (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig.SchedulerResource): - Optional. Resources used by Airflow - schedulers. - web_server (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig.WebServerResource): - Optional. Resources used by Airflow web - server. - worker (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig.WorkerResource): - Optional. Resources used by Airflow workers. - triggerer (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig.TriggererResource): - Optional. Resources used by Airflow - triggerers. - dag_processor (google.cloud.orchestration.airflow.service_v1.types.WorkloadsConfig.DagProcessorResource): - Optional. Resources used by Airflow DAG processors. - - This field is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - """ - - class SchedulerResource(proto.Message): - r"""Configuration for resources used by Airflow schedulers. - - Attributes: - cpu (float): - Optional. CPU request and limit for a single - Airflow scheduler replica. - memory_gb (float): - Optional. Memory (GB) request and limit for a - single Airflow scheduler replica. - storage_gb (float): - Optional. Storage (GB) request and limit for - a single Airflow scheduler replica. - count (int): - Optional. The number of schedulers. - """ - - cpu: float = proto.Field( - proto.FLOAT, - number=1, - ) - memory_gb: float = proto.Field( - proto.FLOAT, - number=2, - ) - storage_gb: float = proto.Field( - proto.FLOAT, - number=3, - ) - count: int = proto.Field( - proto.INT32, - number=4, - ) - - class WebServerResource(proto.Message): - r"""Configuration for resources used by Airflow web server. - - Attributes: - cpu (float): - Optional. CPU request and limit for Airflow - web server. - memory_gb (float): - Optional. Memory (GB) request and limit for - Airflow web server. - storage_gb (float): - Optional. Storage (GB) request and limit for - Airflow web server. - """ - - cpu: float = proto.Field( - proto.FLOAT, - number=1, - ) - memory_gb: float = proto.Field( - proto.FLOAT, - number=2, - ) - storage_gb: float = proto.Field( - proto.FLOAT, - number=3, - ) - - class WorkerResource(proto.Message): - r"""Configuration for resources used by Airflow workers. - - Attributes: - cpu (float): - Optional. CPU request and limit for a single - Airflow worker replica. - memory_gb (float): - Optional. Memory (GB) request and limit for a - single Airflow worker replica. - storage_gb (float): - Optional. Storage (GB) request and limit for - a single Airflow worker replica. - min_count (int): - Optional. Minimum number of workers for - autoscaling. - max_count (int): - Optional. Maximum number of workers for - autoscaling. - """ - - cpu: float = proto.Field( - proto.FLOAT, - number=1, - ) - memory_gb: float = proto.Field( - proto.FLOAT, - number=2, - ) - storage_gb: float = proto.Field( - proto.FLOAT, - number=3, - ) - min_count: int = proto.Field( - proto.INT32, - number=4, - ) - max_count: int = proto.Field( - proto.INT32, - number=5, - ) - - class TriggererResource(proto.Message): - r"""Configuration for resources used by Airflow triggerers. - - Attributes: - count (int): - Optional. The number of triggerers. - cpu (float): - Optional. CPU request and limit for a single - Airflow triggerer replica. - memory_gb (float): - Optional. Memory (GB) request and limit for a - single Airflow triggerer replica. - """ - - count: int = proto.Field( - proto.INT32, - number=1, - ) - cpu: float = proto.Field( - proto.FLOAT, - number=2, - ) - memory_gb: float = proto.Field( - proto.FLOAT, - number=3, - ) - - class DagProcessorResource(proto.Message): - r"""Configuration for resources used by Airflow DAG processors. - - This field is supported for Cloud Composer environments in versions - composer-3-airflow-\ *.*.\ *-build.* and newer. - - Attributes: - cpu (float): - Optional. CPU request and limit for a single - Airflow DAG processor replica. - memory_gb (float): - Optional. Memory (GB) request and limit for a - single Airflow DAG processor replica. - storage_gb (float): - Optional. Storage (GB) request and limit for - a single Airflow DAG processor replica. - count (int): - Optional. The number of DAG processors. If - not provided or set to 0, a single DAG processor - instance will be created. - """ - - cpu: float = proto.Field( - proto.FLOAT, - number=1, - ) - memory_gb: float = proto.Field( - proto.FLOAT, - number=2, - ) - storage_gb: float = proto.Field( - proto.FLOAT, - number=3, - ) - count: int = proto.Field( - proto.INT32, - number=4, - ) - - scheduler: SchedulerResource = proto.Field( - proto.MESSAGE, - number=1, - message=SchedulerResource, - ) - web_server: WebServerResource = proto.Field( - proto.MESSAGE, - number=2, - message=WebServerResource, - ) - worker: WorkerResource = proto.Field( - proto.MESSAGE, - number=3, - message=WorkerResource, - ) - triggerer: TriggererResource = proto.Field( - proto.MESSAGE, - number=4, - message=TriggererResource, - ) - dag_processor: DagProcessorResource = proto.Field( - proto.MESSAGE, - number=5, - message=DagProcessorResource, - ) - - -class RecoveryConfig(proto.Message): - r"""The Recovery settings of an environment. - - Attributes: - scheduled_snapshots_config (google.cloud.orchestration.airflow.service_v1.types.ScheduledSnapshotsConfig): - Optional. The configuration for scheduled - snapshot creation mechanism. - """ - - scheduled_snapshots_config: 'ScheduledSnapshotsConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='ScheduledSnapshotsConfig', - ) - - -class ScheduledSnapshotsConfig(proto.Message): - r"""The configuration for scheduled snapshot creation mechanism. - - Attributes: - enabled (bool): - Optional. Whether scheduled snapshots - creation is enabled. - snapshot_location (str): - Optional. The Cloud Storage location for - storing automatically created snapshots. - snapshot_creation_schedule (str): - Optional. The cron expression representing - the time when snapshots creation mechanism runs. - This field is subject to additional validation - around frequency of execution. - time_zone (str): - Optional. Time zone that sets the context to interpret - snapshot_creation_schedule. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - snapshot_location: str = proto.Field( - proto.STRING, - number=6, - ) - snapshot_creation_schedule: str = proto.Field( - proto.STRING, - number=3, - ) - time_zone: str = proto.Field( - proto.STRING, - number=5, - ) - - -class MasterAuthorizedNetworksConfig(proto.Message): - r"""Configuration options for the master authorized networks - feature. Enabled master authorized networks will disallow all - external traffic to access Kubernetes master through HTTPS - except traffic from the given CIDR blocks, Google Compute Engine - Public IPs and Google Prod IPs. - - Attributes: - enabled (bool): - Whether or not master authorized networks - feature is enabled. - cidr_blocks (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.MasterAuthorizedNetworksConfig.CidrBlock]): - Up to 50 external networks that could access - Kubernetes master through HTTPS. - """ - - class CidrBlock(proto.Message): - r"""CIDR block with an optional name. - - Attributes: - display_name (str): - User-defined name that identifies the CIDR - block. - cidr_block (str): - CIDR block that must be specified in CIDR - notation. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - cidr_block: str = proto.Field( - proto.STRING, - number=2, - ) - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - cidr_blocks: MutableSequence[CidrBlock] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=CidrBlock, - ) - - -class CloudDataLineageIntegration(proto.Message): - r"""Configuration for Cloud Data Lineage integration. - - Attributes: - enabled (bool): - Optional. Whether or not Cloud Data Lineage - integration is enabled. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - - -class Environment(proto.Message): - r"""An environment for running orchestration tasks. - - Attributes: - name (str): - Identifier. The resource name of the - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - EnvironmentId must start with a lowercase letter - followed by up to 63 lowercase letters, numbers, - or hyphens, and cannot end with a hyphen. - config (google.cloud.orchestration.airflow.service_v1.types.EnvironmentConfig): - Optional. Configuration parameters for this - environment. - uuid (str): - Output only. The UUID (Universally Unique - IDentifier) associated with this environment. - This value is generated when the environment is - created. - state (google.cloud.orchestration.airflow.service_v1.types.Environment.State): - The current state of the environment. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - environment was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - environment was last modified. - labels (MutableMapping[str, str]): - Optional. User-defined labels for this environment. The - labels map can contain no more than 64 entries. Entries of - the labels map are UTF8 strings that comply with the - following restrictions: - - - Keys must conform to regexp: - [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62} - - Values must conform to regexp: - [\p{Ll}\p{Lo}\p{N}_-]{0,63} - - Both keys and values are additionally constrained to be - <= 128 bytes in size. - satisfies_pzs (bool): - Output only. Reserved for future use. - satisfies_pzi (bool): - Output only. Reserved for future use. - storage_config (google.cloud.orchestration.airflow.service_v1.types.StorageConfig): - Optional. Storage configuration for this - environment. - """ - class State(proto.Enum): - r"""State of the environment. - - Values: - STATE_UNSPECIFIED (0): - The state of the environment is unknown. - CREATING (1): - The environment is in the process of being - created. - RUNNING (2): - The environment is currently running and - healthy. It is ready for use. - UPDATING (3): - The environment is being updated. It remains - usable but cannot receive additional update - requests or be deleted at this time. - DELETING (4): - The environment is undergoing deletion. It - cannot be used. - ERROR (5): - The environment has encountered an error and - cannot be used. - """ - STATE_UNSPECIFIED = 0 - CREATING = 1 - RUNNING = 2 - UPDATING = 3 - DELETING = 4 - ERROR = 5 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - config: 'EnvironmentConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='EnvironmentConfig', - ) - uuid: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - satisfies_pzs: bool = proto.Field( - proto.BOOL, - number=8, - ) - satisfies_pzi: bool = proto.Field( - proto.BOOL, - number=10, - ) - storage_config: 'StorageConfig' = proto.Field( - proto.MESSAGE, - number=9, - message='StorageConfig', - ) - - -class CheckUpgradeRequest(proto.Message): - r"""Request to check whether image upgrade will succeed. - - Attributes: - environment (str): - Required. The resource name of the - environment to check upgrade for, in the form: - - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - image_version (str): - Optional. The version of the software running in the - environment. This encapsulates both the version of Cloud - Composer functionality and the version of Apache Airflow. It - must match the regular expression - ``composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)``. - When used as input, the server also checks if the provided - version is supported and denies the request for an - unsupported version. - - The Cloud Composer portion of the image version is a full - `semantic version `__, or an alias in - the form of major version number or ``latest``. When an - alias is provided, the server replaces it with the current - Cloud Composer version that satisfies the alias. - - The Apache Airflow portion of the image version is a full - semantic version that points to one of the supported Apache - Airflow versions, or an alias in the form of only major or - major.minor versions specified. When an alias is provided, - the server replaces it with the latest Apache Airflow - version that satisfies the alias and is supported in the - given Cloud Composer version. - - In all cases, the resolved image version is stored in the - same field. - - See also `version - list `__ - and `versioning - overview `__. - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - image_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CheckUpgradeResponse(proto.Message): - r"""Message containing information about the result of an upgrade - check operation. - - Attributes: - build_log_uri (str): - Output only. Url for a docker build log of an - upgraded image. - contains_pypi_modules_conflict (google.cloud.orchestration.airflow.service_v1.types.CheckUpgradeResponse.ConflictResult): - Output only. Whether build has succeeded or - failed on modules conflicts. - pypi_conflict_build_log_extract (str): - Output only. Extract from a docker image - build log containing information about pypi - modules conflicts. - image_version (str): - Composer image for which the build was - happening. - pypi_dependencies (MutableMapping[str, str]): - Pypi dependencies specified in the - environment configuration, at the time when the - build was triggered. - """ - class ConflictResult(proto.Enum): - r"""Whether there were python modules conflict during image - build. - - Values: - CONFLICT_RESULT_UNSPECIFIED (0): - It is unknown whether build had conflicts or - not. - CONFLICT (1): - There were python packages conflicts. - NO_CONFLICT (2): - There were no python packages conflicts. - """ - CONFLICT_RESULT_UNSPECIFIED = 0 - CONFLICT = 1 - NO_CONFLICT = 2 - - build_log_uri: str = proto.Field( - proto.STRING, - number=1, - ) - contains_pypi_modules_conflict: ConflictResult = proto.Field( - proto.ENUM, - number=4, - enum=ConflictResult, - ) - pypi_conflict_build_log_extract: str = proto.Field( - proto.STRING, - number=3, - ) - image_version: str = proto.Field( - proto.STRING, - number=5, - ) - pypi_dependencies: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - - -class DataRetentionConfig(proto.Message): - r"""The configuration setting for Airflow database data retention - mechanism. - - Attributes: - airflow_metadata_retention_config (google.cloud.orchestration.airflow.service_v1.types.AirflowMetadataRetentionPolicyConfig): - Optional. The retention policy for airflow - metadata database. - task_logs_retention_config (google.cloud.orchestration.airflow.service_v1.types.TaskLogsRetentionConfig): - Optional. The configuration settings for task - logs retention - """ - - airflow_metadata_retention_config: 'AirflowMetadataRetentionPolicyConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='AirflowMetadataRetentionPolicyConfig', - ) - task_logs_retention_config: 'TaskLogsRetentionConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='TaskLogsRetentionConfig', - ) - - -class TaskLogsRetentionConfig(proto.Message): - r"""The configuration setting for Task Logs. - - Attributes: - storage_mode (google.cloud.orchestration.airflow.service_v1.types.TaskLogsRetentionConfig.TaskLogsStorageMode): - Optional. The mode of storage for Airflow - workers task logs. - """ - class TaskLogsStorageMode(proto.Enum): - r"""The definition of task_logs_storage_mode. - - Values: - TASK_LOGS_STORAGE_MODE_UNSPECIFIED (0): - This configuration is not specified by the - user. - CLOUD_LOGGING_AND_CLOUD_STORAGE (1): - Store task logs in Cloud Logging and in the - environment's Cloud Storage bucket. - CLOUD_LOGGING_ONLY (2): - Store task logs in Cloud Logging only. - """ - TASK_LOGS_STORAGE_MODE_UNSPECIFIED = 0 - CLOUD_LOGGING_AND_CLOUD_STORAGE = 1 - CLOUD_LOGGING_ONLY = 2 - - storage_mode: TaskLogsStorageMode = proto.Field( - proto.ENUM, - number=2, - enum=TaskLogsStorageMode, - ) - - -class AirflowMetadataRetentionPolicyConfig(proto.Message): - r"""The policy for airflow metadata database retention. - - Attributes: - retention_mode (google.cloud.orchestration.airflow.service_v1.types.AirflowMetadataRetentionPolicyConfig.RetentionMode): - Optional. Retention can be either enabled or - disabled. - retention_days (int): - Optional. How many days data should be - retained for. - """ - class RetentionMode(proto.Enum): - r"""Describes retention policy. - - Values: - RETENTION_MODE_UNSPECIFIED (0): - Default mode doesn't change environment - parameters. - RETENTION_MODE_ENABLED (1): - Retention policy is enabled. - RETENTION_MODE_DISABLED (2): - Retention policy is disabled. - """ - RETENTION_MODE_UNSPECIFIED = 0 - RETENTION_MODE_ENABLED = 1 - RETENTION_MODE_DISABLED = 2 - - retention_mode: RetentionMode = proto.Field( - proto.ENUM, - number=1, - enum=RetentionMode, - ) - retention_days: int = proto.Field( - proto.INT32, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/image_versions.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/image_versions.py deleted file mode 100644 index c5a7567cdb33..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/image_versions.py +++ /dev/null @@ -1,148 +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.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.orchestration.airflow.service.v1', - manifest={ - 'ListImageVersionsRequest', - 'ListImageVersionsResponse', - 'ImageVersion', - }, -) - - -class ListImageVersionsRequest(proto.Message): - r"""List ImageVersions in a project and location. - - Attributes: - parent (str): - List ImageVersions in the given project and - location, in the form: - "projects/{projectId}/locations/{locationId}". - page_size (int): - The maximum number of image_versions to return. - page_token (str): - The next_page_token value returned from a previous List - request, if any. - include_past_releases (bool): - Whether or not image versions from old - releases should be included. - """ - - 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, - ) - include_past_releases: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class ListImageVersionsResponse(proto.Message): - r"""The ImageVersions in a project and location. - - Attributes: - image_versions (MutableSequence[google.cloud.orchestration.airflow.service_v1.types.ImageVersion]): - The list of supported ImageVersions in a - location. - next_page_token (str): - The page token used to query for the next - page if one exists. - """ - - @property - def raw_page(self): - return self - - image_versions: MutableSequence['ImageVersion'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ImageVersion', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ImageVersion(proto.Message): - r"""ImageVersion information - - Attributes: - image_version_id (str): - The string identifier of the ImageVersion, in - the form: "composer-x.y.z-airflow-a.b.c". - is_default (bool): - Whether this is the default ImageVersion used - by Composer during environment creation if no - input ImageVersion is specified. - supported_python_versions (MutableSequence[str]): - supported python versions - release_date (google.type.date_pb2.Date): - The date of the version release. - creation_disabled (bool): - Whether it is impossible to create an - environment with the image version. - upgrade_disabled (bool): - Whether it is impossible to upgrade an - environment running with the image version. - """ - - image_version_id: str = proto.Field( - proto.STRING, - number=1, - ) - is_default: bool = proto.Field( - proto.BOOL, - number=2, - ) - supported_python_versions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - release_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=4, - message=date_pb2.Date, - ) - creation_disabled: bool = proto.Field( - proto.BOOL, - number=5, - ) - upgrade_disabled: bool = proto.Field( - proto.BOOL, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/operations.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/operations.py deleted file mode 100644 index cd908b4ed10c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/operations.py +++ /dev/null @@ -1,147 +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.orchestration.airflow.service.v1', - manifest={ - 'OperationMetadata', - }, -) - - -class OperationMetadata(proto.Message): - r"""Metadata describing an operation. - - Attributes: - state (google.cloud.orchestration.airflow.service_v1.types.OperationMetadata.State): - Output only. The current operation state. - operation_type (google.cloud.orchestration.airflow.service_v1.types.OperationMetadata.Type): - Output only. The type of operation being - performed. - resource (str): - Output only. The resource being operated on, as a `relative - resource - name `__. - resource_uuid (str): - Output only. The UUID of the resource being - operated on. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation was - submitted to the server. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the operation - terminated, regardless of its success. This - field is unset if the operation is still - ongoing. - """ - class State(proto.Enum): - r"""An enum describing the overall state of an operation. - - Values: - STATE_UNSPECIFIED (0): - Unused. - PENDING (1): - The operation has been created but is not yet - started. - RUNNING (2): - The operation is underway. - SUCCEEDED (3): - The operation completed successfully. - SUCCESSFUL (3): - No description available. - FAILED (4): - The operation is no longer running but did - not succeed. - """ - _pb_options = {'allow_alias': True} - STATE_UNSPECIFIED = 0 - PENDING = 1 - RUNNING = 2 - SUCCEEDED = 3 - SUCCESSFUL = 3 - FAILED = 4 - - class Type(proto.Enum): - r"""Type of longrunning operation. - - Values: - TYPE_UNSPECIFIED (0): - Unused. - CREATE (1): - A resource creation operation. - DELETE (2): - A resource deletion operation. - UPDATE (3): - A resource update operation. - CHECK (4): - A resource check operation. - SAVE_SNAPSHOT (5): - Saves snapshot of the resource operation. - LOAD_SNAPSHOT (6): - Loads snapshot of the resource operation. - DATABASE_FAILOVER (7): - Triggers failover of environment's Cloud SQL - instance (only for highly resilient - environments). - """ - TYPE_UNSPECIFIED = 0 - CREATE = 1 - DELETE = 2 - UPDATE = 3 - CHECK = 4 - SAVE_SNAPSHOT = 5 - LOAD_SNAPSHOT = 6 - DATABASE_FAILOVER = 7 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - operation_type: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - resource: str = proto.Field( - proto.STRING, - number=3, - ) - resource_uuid: str = proto.Field( - proto.STRING, - number=4, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/mypy.ini b/owl-bot-staging/google-cloud-orchestration-airflow/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/noxfile.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/noxfile.py deleted file mode 100644 index edbe3113b046..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow' - -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/orchestration/airflow/service_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/orchestration/airflow/service_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-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_async.py deleted file mode 100644 index 6b0d1d7e863b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_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 CheckUpgrade -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_CheckUpgrade_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.orchestration.airflow import service_v1 - - -async def sample_check_upgrade(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.CheckUpgradeRequest( - environment="environment_value", - ) - - # Make the request - operation = client.check_upgrade(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_CheckUpgrade_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_sync.py deleted file mode 100644 index f8e30156ed47..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_check_upgrade_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 CheckUpgrade -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_CheckUpgrade_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.orchestration.airflow import service_v1 - - -def sample_check_upgrade(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.CheckUpgradeRequest( - environment="environment_value", - ) - - # Make the request - operation = client.check_upgrade(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_CheckUpgrade_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py deleted file mode 100644 index 9b5084ab9e58..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_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 CreateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_CreateEnvironment_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.orchestration.airflow import service_v1 - - -async def sample_create_environment(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.CreateEnvironmentRequest( - ) - - # Make the request - operation = client.create_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_CreateEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py deleted file mode 100644 index b158ae726fdc..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_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 CreateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_CreateEnvironment_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.orchestration.airflow import service_v1 - - -def sample_create_environment(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.CreateEnvironmentRequest( - ) - - # Make the request - operation = client.create_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_CreateEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_async.py deleted file mode 100644 index 5ff6619dd120..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_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 CreateUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 - - -async def sample_create_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.CreateUserWorkloadsConfigMapRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_sync.py deleted file mode 100644 index 6555bb873a67..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_config_map_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 CreateUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 - - -def sample_create_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.CreateUserWorkloadsConfigMapRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_async.py deleted file mode 100644 index 224e00ca8610..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_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 CreateUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_CreateUserWorkloadsSecret_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.orchestration.airflow import service_v1 - - -async def sample_create_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.CreateUserWorkloadsSecretRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_CreateUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_sync.py deleted file mode 100644 index 5005b96f04d0..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_user_workloads_secret_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 CreateUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_CreateUserWorkloadsSecret_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.orchestration.airflow import service_v1 - - -def sample_create_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.CreateUserWorkloadsSecretRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_CreateUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py deleted file mode 100644 index e7fdea54a032..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_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 DatabaseFailover -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_DatabaseFailover_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.orchestration.airflow import service_v1 - - -async def sample_database_failover(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.DatabaseFailoverRequest( - ) - - # Make the request - operation = client.database_failover(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_DatabaseFailover_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py deleted file mode 100644 index 6ca611bf168e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_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 DatabaseFailover -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_DatabaseFailover_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.orchestration.airflow import service_v1 - - -def sample_database_failover(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.DatabaseFailoverRequest( - ) - - # Make the request - operation = client.database_failover(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_DatabaseFailover_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py deleted file mode 100644 index 101b8e274104..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_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 DeleteEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_DeleteEnvironment_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.orchestration.airflow import service_v1 - - -async def sample_delete_environment(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.DeleteEnvironmentRequest( - ) - - # Make the request - operation = client.delete_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_DeleteEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py deleted file mode 100644 index f9b835930e03..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_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 DeleteEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_DeleteEnvironment_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.orchestration.airflow import service_v1 - - -def sample_delete_environment(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.DeleteEnvironmentRequest( - ) - - # Make the request - operation = client.delete_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_DeleteEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_async.py deleted file mode 100644 index 82f45b706fba..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_async.py +++ /dev/null @@ -1,50 +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 DeleteUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 - - -async def sample_delete_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.DeleteUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - await client.delete_user_workloads_config_map(request=request) - - -# [END composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_sync.py deleted file mode 100644 index daac15ef4ff3..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_config_map_sync.py +++ /dev/null @@ -1,50 +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 DeleteUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 - - -def sample_delete_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.DeleteUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - client.delete_user_workloads_config_map(request=request) - - -# [END composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_async.py deleted file mode 100644 index beb6e11148e5..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_async.py +++ /dev/null @@ -1,50 +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 DeleteUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_DeleteUserWorkloadsSecret_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.orchestration.airflow import service_v1 - - -async def sample_delete_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.DeleteUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - await client.delete_user_workloads_secret(request=request) - - -# [END composer_v1_generated_Environments_DeleteUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_sync.py deleted file mode 100644 index 34ee80effba2..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_user_workloads_secret_sync.py +++ /dev/null @@ -1,50 +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 DeleteUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_DeleteUserWorkloadsSecret_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.orchestration.airflow import service_v1 - - -def sample_delete_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.DeleteUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - client.delete_user_workloads_secret(request=request) - - -# [END composer_v1_generated_Environments_DeleteUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py deleted file mode 100644 index 6eca2e668f9a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExecuteAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_ExecuteAirflowCommand_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.orchestration.airflow import service_v1 - - -async def sample_execute_airflow_command(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ExecuteAirflowCommandRequest( - ) - - # Make the request - response = await client.execute_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_ExecuteAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py deleted file mode 100644 index 723d39ddffdf..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExecuteAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_ExecuteAirflowCommand_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.orchestration.airflow import service_v1 - - -def sample_execute_airflow_command(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.ExecuteAirflowCommandRequest( - ) - - # Make the request - response = client.execute_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_ExecuteAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py deleted file mode 100644 index dcafb0a9023d..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_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 FetchDatabaseProperties -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_FetchDatabaseProperties_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.orchestration.airflow import service_v1 - - -async def sample_fetch_database_properties(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.FetchDatabasePropertiesRequest( - environment="environment_value", - ) - - # Make the request - response = await client.fetch_database_properties(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_FetchDatabaseProperties_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py deleted file mode 100644 index 311816055325..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_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 FetchDatabaseProperties -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_FetchDatabaseProperties_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.orchestration.airflow import service_v1 - - -def sample_fetch_database_properties(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.FetchDatabasePropertiesRequest( - environment="environment_value", - ) - - # Make the request - response = client.fetch_database_properties(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_FetchDatabaseProperties_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py deleted file mode 100644 index 2c5ea9803969..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_GetEnvironment_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.orchestration.airflow import service_v1 - - -async def sample_get_environment(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.GetEnvironmentRequest( - ) - - # Make the request - response = await client.get_environment(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_GetEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py deleted file mode 100644 index f1655bd86f35..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_GetEnvironment_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.orchestration.airflow import service_v1 - - -def sample_get_environment(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.GetEnvironmentRequest( - ) - - # Make the request - response = client.get_environment(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_GetEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_async.py deleted file mode 100644 index aedfd3649839..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_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 GetUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_GetUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 - - -async def sample_get_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.GetUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_GetUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_sync.py deleted file mode 100644 index c7c245d66794..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_config_map_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 GetUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_GetUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 - - -def sample_get_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.GetUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - response = client.get_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_GetUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_async.py deleted file mode 100644 index 71ad443f6408..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_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 GetUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_GetUserWorkloadsSecret_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.orchestration.airflow import service_v1 - - -async def sample_get_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.GetUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_GetUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_sync.py deleted file mode 100644 index 3b22c2bc7c18..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_user_workloads_secret_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 GetUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_GetUserWorkloadsSecret_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.orchestration.airflow import service_v1 - - -def sample_get_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.GetUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - response = client.get_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_GetUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py deleted file mode 100644 index 3c01b1b9694f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_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 ListEnvironments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_ListEnvironments_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.orchestration.airflow import service_v1 - - -async def sample_list_environments(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ListEnvironmentsRequest( - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END composer_v1_generated_Environments_ListEnvironments_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py deleted file mode 100644 index b801f09b44d4..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_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 ListEnvironments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_ListEnvironments_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.orchestration.airflow import service_v1 - - -def sample_list_environments(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.ListEnvironmentsRequest( - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END composer_v1_generated_Environments_ListEnvironments_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_async.py deleted file mode 100644 index 7d95cf57d729..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_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 ListUserWorkloadsConfigMaps -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_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.orchestration.airflow import service_v1 - - -async def sample_list_user_workloads_config_maps(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ListUserWorkloadsConfigMapsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_config_maps(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_sync.py deleted file mode 100644 index de0179278426..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_config_maps_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 ListUserWorkloadsConfigMaps -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_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.orchestration.airflow import service_v1 - - -def sample_list_user_workloads_config_maps(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.ListUserWorkloadsConfigMapsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_config_maps(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_async.py deleted file mode 100644 index 4634b9457358..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_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 ListUserWorkloadsSecrets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_ListUserWorkloadsSecrets_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.orchestration.airflow import service_v1 - - -async def sample_list_user_workloads_secrets(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ListUserWorkloadsSecretsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_secrets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END composer_v1_generated_Environments_ListUserWorkloadsSecrets_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_sync.py deleted file mode 100644 index 72406bc3eb93..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_user_workloads_secrets_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 ListUserWorkloadsSecrets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_ListUserWorkloadsSecrets_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.orchestration.airflow import service_v1 - - -def sample_list_user_workloads_secrets(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.ListUserWorkloadsSecretsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_secrets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END composer_v1_generated_Environments_ListUserWorkloadsSecrets_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_async.py deleted file mode 100644 index a8fe64b38179..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_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 ListWorkloads -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_ListWorkloads_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.orchestration.airflow import service_v1 - - -async def sample_list_workloads(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ListWorkloadsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workloads(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END composer_v1_generated_Environments_ListWorkloads_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_sync.py deleted file mode 100644 index 7131f654cf05..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_workloads_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 ListWorkloads -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_ListWorkloads_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.orchestration.airflow import service_v1 - - -def sample_list_workloads(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.ListWorkloadsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workloads(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END composer_v1_generated_Environments_ListWorkloads_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py deleted file mode 100644 index 853a8d1fba0c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_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 LoadSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_LoadSnapshot_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.orchestration.airflow import service_v1 - - -async def sample_load_snapshot(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.LoadSnapshotRequest( - ) - - # Make the request - operation = client.load_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_LoadSnapshot_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py deleted file mode 100644 index a7896be32d11..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_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 LoadSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_LoadSnapshot_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.orchestration.airflow import service_v1 - - -def sample_load_snapshot(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.LoadSnapshotRequest( - ) - - # Make the request - operation = client.load_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_LoadSnapshot_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py deleted file mode 100644 index 16becaef7d3f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PollAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_PollAirflowCommand_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.orchestration.airflow import service_v1 - - -async def sample_poll_airflow_command(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.PollAirflowCommandRequest( - ) - - # Make the request - response = await client.poll_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_PollAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py deleted file mode 100644 index 818dd2893280..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PollAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_PollAirflowCommand_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.orchestration.airflow import service_v1 - - -def sample_poll_airflow_command(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.PollAirflowCommandRequest( - ) - - # Make the request - response = client.poll_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_PollAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py deleted file mode 100644 index cb732a47e996..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_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 SaveSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_SaveSnapshot_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.orchestration.airflow import service_v1 - - -async def sample_save_snapshot(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.SaveSnapshotRequest( - ) - - # Make the request - operation = client.save_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_SaveSnapshot_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py deleted file mode 100644 index cf0091fdb149..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_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 SaveSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_SaveSnapshot_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.orchestration.airflow import service_v1 - - -def sample_save_snapshot(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.SaveSnapshotRequest( - ) - - # Make the request - operation = client.save_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_SaveSnapshot_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py deleted file mode 100644 index 8c5a0204f31f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StopAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_StopAirflowCommand_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.orchestration.airflow import service_v1 - - -async def sample_stop_airflow_command(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.StopAirflowCommandRequest( - ) - - # Make the request - response = await client.stop_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_StopAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py deleted file mode 100644 index 8528a3fa9f91..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StopAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_StopAirflowCommand_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.orchestration.airflow import service_v1 - - -def sample_stop_airflow_command(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.StopAirflowCommandRequest( - ) - - # Make the request - response = client.stop_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_StopAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py deleted file mode 100644 index 6ffaec1b46a9..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_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 UpdateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_UpdateEnvironment_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.orchestration.airflow import service_v1 - - -async def sample_update_environment(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.UpdateEnvironmentRequest( - ) - - # Make the request - operation = client.update_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_UpdateEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py deleted file mode 100644 index 5bde272c7c12..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_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 UpdateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_UpdateEnvironment_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.orchestration.airflow import service_v1 - - -def sample_update_environment(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.UpdateEnvironmentRequest( - ) - - # Make the request - operation = client.update_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_UpdateEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_async.py deleted file mode 100644 index cb78e06beea8..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 - - -async def sample_update_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.UpdateUserWorkloadsConfigMapRequest( - ) - - # Make the request - response = await client.update_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_sync.py deleted file mode 100644 index 77c192805865..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_config_map_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1 - - -def sample_update_user_workloads_config_map(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.UpdateUserWorkloadsConfigMapRequest( - ) - - # Make the request - response = client.update_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_async.py deleted file mode 100644 index 339020bb8b0d..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_UpdateUserWorkloadsSecret_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.orchestration.airflow import service_v1 - - -async def sample_update_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1.UpdateUserWorkloadsSecretRequest( - ) - - # Make the request - response = await client.update_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_UpdateUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_sync.py deleted file mode 100644 index 307caed04c66..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_user_workloads_secret_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_Environments_UpdateUserWorkloadsSecret_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.orchestration.airflow import service_v1 - - -def sample_update_user_workloads_secret(): - # Create a client - client = service_v1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1.UpdateUserWorkloadsSecretRequest( - ) - - # Make the request - response = client.update_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1_generated_Environments_UpdateUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_async.py deleted file mode 100644 index 66e9c5c442b6..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_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 ListImageVersions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_ImageVersions_ListImageVersions_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.orchestration.airflow import service_v1 - - -async def sample_list_image_versions(): - # Create a client - client = service_v1.ImageVersionsAsyncClient() - - # Initialize request argument(s) - request = service_v1.ListImageVersionsRequest( - ) - - # Make the request - page_result = client.list_image_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END composer_v1_generated_ImageVersions_ListImageVersions_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_sync.py deleted file mode 100644 index 0506674847be..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_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 ListImageVersions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow - - -# [START composer_v1_generated_ImageVersions_ListImageVersions_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.orchestration.airflow import service_v1 - - -def sample_list_image_versions(): - # Create a client - client = service_v1.ImageVersionsClient() - - # Initialize request argument(s) - request = service_v1.ListImageVersionsRequest( - ) - - # Make the request - page_result = client.list_image_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END composer_v1_generated_ImageVersions_ListImageVersions_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json b/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json deleted file mode 100644 index 37f3c1f31434..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json +++ /dev/null @@ -1,4004 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.orchestration.airflow.service.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-orchestration-airflow", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.check_upgrade", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CheckUpgrade", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "CheckUpgrade" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.CheckUpgradeRequest" - }, - { - "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": "check_upgrade" - }, - "description": "Sample for CheckUpgrade", - "file": "composer_v1_generated_environments_check_upgrade_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_CheckUpgrade_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": "composer_v1_generated_environments_check_upgrade_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.check_upgrade", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CheckUpgrade", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "CheckUpgrade" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.CheckUpgradeRequest" - }, - { - "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": "check_upgrade" - }, - "description": "Sample for CheckUpgrade", - "file": "composer_v1_generated_environments_check_upgrade_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_CheckUpgrade_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": "composer_v1_generated_environments_check_upgrade_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.create_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.CreateEnvironmentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "environment", - "type": "google.cloud.orchestration.airflow.service_v1.types.Environment" - }, - { - "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_environment" - }, - "description": "Sample for CreateEnvironment", - "file": "composer_v1_generated_environments_create_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_CreateEnvironment_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_create_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.create_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.CreateEnvironmentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "environment", - "type": "google.cloud.orchestration.airflow.service_v1.types.Environment" - }, - { - "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_environment" - }, - "description": "Sample for CreateEnvironment", - "file": "composer_v1_generated_environments_create_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_CreateEnvironment_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_create_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.create_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsConfigMapRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user_workloads_config_map", - "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", - "shortName": "create_user_workloads_config_map" - }, - "description": "Sample for CreateUserWorkloadsConfigMap", - "file": "composer_v1_generated_environments_create_user_workloads_config_map_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_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": "composer_v1_generated_environments_create_user_workloads_config_map_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.create_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsConfigMapRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user_workloads_config_map", - "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", - "shortName": "create_user_workloads_config_map" - }, - "description": "Sample for CreateUserWorkloadsConfigMap", - "file": "composer_v1_generated_environments_create_user_workloads_config_map_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_CreateUserWorkloadsConfigMap_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": "composer_v1_generated_environments_create_user_workloads_config_map_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.create_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsSecretRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user_workloads_secret", - "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret", - "shortName": "create_user_workloads_secret" - }, - "description": "Sample for CreateUserWorkloadsSecret", - "file": "composer_v1_generated_environments_create_user_workloads_secret_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_CreateUserWorkloadsSecret_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": "composer_v1_generated_environments_create_user_workloads_secret_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.create_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.CreateUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.CreateUserWorkloadsSecretRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user_workloads_secret", - "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret", - "shortName": "create_user_workloads_secret" - }, - "description": "Sample for CreateUserWorkloadsSecret", - "file": "composer_v1_generated_environments_create_user_workloads_secret_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_CreateUserWorkloadsSecret_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": "composer_v1_generated_environments_create_user_workloads_secret_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.database_failover", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DatabaseFailover", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "DatabaseFailover" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.DatabaseFailoverRequest" - }, - { - "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": "database_failover" - }, - "description": "Sample for DatabaseFailover", - "file": "composer_v1_generated_environments_database_failover_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_DatabaseFailover_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_database_failover_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.database_failover", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DatabaseFailover", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "DatabaseFailover" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.DatabaseFailoverRequest" - }, - { - "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": "database_failover" - }, - "description": "Sample for DatabaseFailover", - "file": "composer_v1_generated_environments_database_failover_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_DatabaseFailover_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_database_failover_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.delete_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteEnvironmentRequest" - }, - { - "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_environment" - }, - "description": "Sample for DeleteEnvironment", - "file": "composer_v1_generated_environments_delete_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_DeleteEnvironment_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_delete_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.delete_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteEnvironmentRequest" - }, - { - "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_environment" - }, - "description": "Sample for DeleteEnvironment", - "file": "composer_v1_generated_environments_delete_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_DeleteEnvironment_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_delete_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.delete_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsConfigMapRequest" - }, - { - "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]]]" - } - ], - "shortName": "delete_user_workloads_config_map" - }, - "description": "Sample for DeleteUserWorkloadsConfigMap", - "file": "composer_v1_generated_environments_delete_user_workloads_config_map_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_delete_user_workloads_config_map_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.delete_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsConfigMapRequest" - }, - { - "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]]]" - } - ], - "shortName": "delete_user_workloads_config_map" - }, - "description": "Sample for DeleteUserWorkloadsConfigMap", - "file": "composer_v1_generated_environments_delete_user_workloads_config_map_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_DeleteUserWorkloadsConfigMap_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_delete_user_workloads_config_map_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.delete_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsSecretRequest" - }, - { - "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]]]" - } - ], - "shortName": "delete_user_workloads_secret" - }, - "description": "Sample for DeleteUserWorkloadsSecret", - "file": "composer_v1_generated_environments_delete_user_workloads_secret_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_DeleteUserWorkloadsSecret_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_delete_user_workloads_secret_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.delete_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.DeleteUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.DeleteUserWorkloadsSecretRequest" - }, - { - "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]]]" - } - ], - "shortName": "delete_user_workloads_secret" - }, - "description": "Sample for DeleteUserWorkloadsSecret", - "file": "composer_v1_generated_environments_delete_user_workloads_secret_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_DeleteUserWorkloadsSecret_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_delete_user_workloads_secret_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.execute_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ExecuteAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "ExecuteAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandResponse", - "shortName": "execute_airflow_command" - }, - "description": "Sample for ExecuteAirflowCommand", - "file": "composer_v1_generated_environments_execute_airflow_command_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_ExecuteAirflowCommand_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_execute_airflow_command_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.execute_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ExecuteAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "ExecuteAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.ExecuteAirflowCommandResponse", - "shortName": "execute_airflow_command" - }, - "description": "Sample for ExecuteAirflowCommand", - "file": "composer_v1_generated_environments_execute_airflow_command_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_ExecuteAirflowCommand_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_execute_airflow_command_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.fetch_database_properties", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.FetchDatabaseProperties", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "FetchDatabaseProperties" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesResponse", - "shortName": "fetch_database_properties" - }, - "description": "Sample for FetchDatabaseProperties", - "file": "composer_v1_generated_environments_fetch_database_properties_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_FetchDatabaseProperties_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": "composer_v1_generated_environments_fetch_database_properties_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.fetch_database_properties", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.FetchDatabaseProperties", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "FetchDatabaseProperties" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.FetchDatabasePropertiesResponse", - "shortName": "fetch_database_properties" - }, - "description": "Sample for FetchDatabaseProperties", - "file": "composer_v1_generated_environments_fetch_database_properties_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_FetchDatabaseProperties_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": "composer_v1_generated_environments_fetch_database_properties_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.get_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.GetEnvironmentRequest" - }, - { - "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.orchestration.airflow.service_v1.types.Environment", - "shortName": "get_environment" - }, - "description": "Sample for GetEnvironment", - "file": "composer_v1_generated_environments_get_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_GetEnvironment_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_get_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.get_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.GetEnvironmentRequest" - }, - { - "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.orchestration.airflow.service_v1.types.Environment", - "shortName": "get_environment" - }, - "description": "Sample for GetEnvironment", - "file": "composer_v1_generated_environments_get_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_GetEnvironment_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_get_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.get_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "GetUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsConfigMapRequest" - }, - { - "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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", - "shortName": "get_user_workloads_config_map" - }, - "description": "Sample for GetUserWorkloadsConfigMap", - "file": "composer_v1_generated_environments_get_user_workloads_config_map_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_GetUserWorkloadsConfigMap_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": "composer_v1_generated_environments_get_user_workloads_config_map_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.get_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "GetUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsConfigMapRequest" - }, - { - "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.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", - "shortName": "get_user_workloads_config_map" - }, - "description": "Sample for GetUserWorkloadsConfigMap", - "file": "composer_v1_generated_environments_get_user_workloads_config_map_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_GetUserWorkloadsConfigMap_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": "composer_v1_generated_environments_get_user_workloads_config_map_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.get_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "GetUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsSecretRequest" - }, - { - "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.orchestration.airflow.service_v1.types.UserWorkloadsSecret", - "shortName": "get_user_workloads_secret" - }, - "description": "Sample for GetUserWorkloadsSecret", - "file": "composer_v1_generated_environments_get_user_workloads_secret_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_GetUserWorkloadsSecret_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": "composer_v1_generated_environments_get_user_workloads_secret_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.get_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.GetUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "GetUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.GetUserWorkloadsSecretRequest" - }, - { - "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.orchestration.airflow.service_v1.types.UserWorkloadsSecret", - "shortName": "get_user_workloads_secret" - }, - "description": "Sample for GetUserWorkloadsSecret", - "file": "composer_v1_generated_environments_get_user_workloads_secret_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_GetUserWorkloadsSecret_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": "composer_v1_generated_environments_get_user_workloads_secret_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.list_environments", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListEnvironments", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "ListEnvironments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest" - }, - { - "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.orchestration.airflow.service_v1.services.environments.pagers.ListEnvironmentsAsyncPager", - "shortName": "list_environments" - }, - "description": "Sample for ListEnvironments", - "file": "composer_v1_generated_environments_list_environments_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_ListEnvironments_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_list_environments_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.list_environments", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListEnvironments", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "ListEnvironments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest" - }, - { - "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.orchestration.airflow.service_v1.services.environments.pagers.ListEnvironmentsPager", - "shortName": "list_environments" - }, - "description": "Sample for ListEnvironments", - "file": "composer_v1_generated_environments_list_environments_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_ListEnvironments_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_list_environments_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.list_user_workloads_config_maps", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListUserWorkloadsConfigMaps", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "ListUserWorkloadsConfigMaps" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest" - }, - { - "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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsConfigMapsAsyncPager", - "shortName": "list_user_workloads_config_maps" - }, - "description": "Sample for ListUserWorkloadsConfigMaps", - "file": "composer_v1_generated_environments_list_user_workloads_config_maps_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_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": "composer_v1_generated_environments_list_user_workloads_config_maps_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.list_user_workloads_config_maps", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListUserWorkloadsConfigMaps", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "ListUserWorkloadsConfigMaps" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest" - }, - { - "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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsConfigMapsPager", - "shortName": "list_user_workloads_config_maps" - }, - "description": "Sample for ListUserWorkloadsConfigMaps", - "file": "composer_v1_generated_environments_list_user_workloads_config_maps_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_ListUserWorkloadsConfigMaps_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": "composer_v1_generated_environments_list_user_workloads_config_maps_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.list_user_workloads_secrets", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListUserWorkloadsSecrets", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "ListUserWorkloadsSecrets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest" - }, - { - "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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsSecretsAsyncPager", - "shortName": "list_user_workloads_secrets" - }, - "description": "Sample for ListUserWorkloadsSecrets", - "file": "composer_v1_generated_environments_list_user_workloads_secrets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_ListUserWorkloadsSecrets_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": "composer_v1_generated_environments_list_user_workloads_secrets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.list_user_workloads_secrets", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListUserWorkloadsSecrets", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "ListUserWorkloadsSecrets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest" - }, - { - "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.orchestration.airflow.service_v1.services.environments.pagers.ListUserWorkloadsSecretsPager", - "shortName": "list_user_workloads_secrets" - }, - "description": "Sample for ListUserWorkloadsSecrets", - "file": "composer_v1_generated_environments_list_user_workloads_secrets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_ListUserWorkloadsSecrets_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": "composer_v1_generated_environments_list_user_workloads_secrets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.list_workloads", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListWorkloads", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "ListWorkloads" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest" - }, - { - "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.orchestration.airflow.service_v1.services.environments.pagers.ListWorkloadsAsyncPager", - "shortName": "list_workloads" - }, - "description": "Sample for ListWorkloads", - "file": "composer_v1_generated_environments_list_workloads_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_ListWorkloads_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": "composer_v1_generated_environments_list_workloads_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.list_workloads", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.ListWorkloads", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "ListWorkloads" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest" - }, - { - "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.orchestration.airflow.service_v1.services.environments.pagers.ListWorkloadsPager", - "shortName": "list_workloads" - }, - "description": "Sample for ListWorkloads", - "file": "composer_v1_generated_environments_list_workloads_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_ListWorkloads_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": "composer_v1_generated_environments_list_workloads_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.load_snapshot", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.LoadSnapshot", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "LoadSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.LoadSnapshotRequest" - }, - { - "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": "load_snapshot" - }, - "description": "Sample for LoadSnapshot", - "file": "composer_v1_generated_environments_load_snapshot_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_LoadSnapshot_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_load_snapshot_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.load_snapshot", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.LoadSnapshot", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "LoadSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.LoadSnapshotRequest" - }, - { - "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": "load_snapshot" - }, - "description": "Sample for LoadSnapshot", - "file": "composer_v1_generated_environments_load_snapshot_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_LoadSnapshot_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_load_snapshot_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.poll_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.PollAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "PollAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandResponse", - "shortName": "poll_airflow_command" - }, - "description": "Sample for PollAirflowCommand", - "file": "composer_v1_generated_environments_poll_airflow_command_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_PollAirflowCommand_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_poll_airflow_command_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.poll_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.PollAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "PollAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.PollAirflowCommandResponse", - "shortName": "poll_airflow_command" - }, - "description": "Sample for PollAirflowCommand", - "file": "composer_v1_generated_environments_poll_airflow_command_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_PollAirflowCommand_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_poll_airflow_command_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.save_snapshot", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.SaveSnapshot", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "SaveSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.SaveSnapshotRequest" - }, - { - "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": "save_snapshot" - }, - "description": "Sample for SaveSnapshot", - "file": "composer_v1_generated_environments_save_snapshot_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_SaveSnapshot_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_save_snapshot_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.save_snapshot", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.SaveSnapshot", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "SaveSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.SaveSnapshotRequest" - }, - { - "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": "save_snapshot" - }, - "description": "Sample for SaveSnapshot", - "file": "composer_v1_generated_environments_save_snapshot_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_SaveSnapshot_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_save_snapshot_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.stop_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.StopAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "StopAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandResponse", - "shortName": "stop_airflow_command" - }, - "description": "Sample for StopAirflowCommand", - "file": "composer_v1_generated_environments_stop_airflow_command_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_StopAirflowCommand_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_stop_airflow_command_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.stop_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.StopAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "StopAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.StopAirflowCommandResponse", - "shortName": "stop_airflow_command" - }, - "description": "Sample for StopAirflowCommand", - "file": "composer_v1_generated_environments_stop_airflow_command_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_StopAirflowCommand_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_stop_airflow_command_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.update_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateEnvironmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "environment", - "type": "google.cloud.orchestration.airflow.service_v1.types.Environment" - }, - { - "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_environment" - }, - "description": "Sample for UpdateEnvironment", - "file": "composer_v1_generated_environments_update_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_UpdateEnvironment_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_update_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.update_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateEnvironmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "environment", - "type": "google.cloud.orchestration.airflow.service_v1.types.Environment" - }, - { - "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_environment" - }, - "description": "Sample for UpdateEnvironment", - "file": "composer_v1_generated_environments_update_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_UpdateEnvironment_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_update_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.update_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsConfigMapRequest" - }, - { - "name": "user_workloads_config_map", - "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", - "shortName": "update_user_workloads_config_map" - }, - "description": "Sample for UpdateUserWorkloadsConfigMap", - "file": "composer_v1_generated_environments_update_user_workloads_config_map_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_update_user_workloads_config_map_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.update_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsConfigMapRequest" - }, - { - "name": "user_workloads_config_map", - "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsConfigMap", - "shortName": "update_user_workloads_config_map" - }, - "description": "Sample for UpdateUserWorkloadsConfigMap", - "file": "composer_v1_generated_environments_update_user_workloads_config_map_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_UpdateUserWorkloadsConfigMap_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_update_user_workloads_config_map_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsAsyncClient.update_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsSecretRequest" - }, - { - "name": "user_workloads_secret", - "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret", - "shortName": "update_user_workloads_secret" - }, - "description": "Sample for UpdateUserWorkloadsSecret", - "file": "composer_v1_generated_environments_update_user_workloads_secret_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_UpdateUserWorkloadsSecret_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_update_user_workloads_secret_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.EnvironmentsClient.update_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments.UpdateUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.UpdateUserWorkloadsSecretRequest" - }, - { - "name": "user_workloads_secret", - "type": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1.types.UserWorkloadsSecret", - "shortName": "update_user_workloads_secret" - }, - "description": "Sample for UpdateUserWorkloadsSecret", - "file": "composer_v1_generated_environments_update_user_workloads_secret_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_Environments_UpdateUserWorkloadsSecret_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_environments_update_user_workloads_secret_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.ImageVersionsAsyncClient", - "shortName": "ImageVersionsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.ImageVersionsAsyncClient.list_image_versions", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.ImageVersions.ListImageVersions", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "shortName": "ImageVersions" - }, - "shortName": "ListImageVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest" - }, - { - "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.orchestration.airflow.service_v1.services.image_versions.pagers.ListImageVersionsAsyncPager", - "shortName": "list_image_versions" - }, - "description": "Sample for ListImageVersions", - "file": "composer_v1_generated_image_versions_list_image_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_ImageVersions_ListImageVersions_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_image_versions_list_image_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1.ImageVersionsClient", - "shortName": "ImageVersionsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1.ImageVersionsClient.list_image_versions", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1.ImageVersions.ListImageVersions", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1.ImageVersions", - "shortName": "ImageVersions" - }, - "shortName": "ListImageVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest" - }, - { - "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.orchestration.airflow.service_v1.services.image_versions.pagers.ListImageVersionsPager", - "shortName": "list_image_versions" - }, - "description": "Sample for ListImageVersions", - "file": "composer_v1_generated_image_versions_list_image_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1_generated_ImageVersions_ListImageVersions_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1_generated_image_versions_list_image_versions_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py deleted file mode 100644 index 1d453d96293f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py +++ /dev/null @@ -1,200 +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 serviceCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'check_upgrade': ('environment', 'image_version', ), - 'create_environment': ('parent', 'environment', ), - 'create_user_workloads_config_map': ('parent', 'user_workloads_config_map', ), - 'create_user_workloads_secret': ('parent', 'user_workloads_secret', ), - 'database_failover': ('environment', ), - 'delete_environment': ('name', ), - 'delete_user_workloads_config_map': ('name', ), - 'delete_user_workloads_secret': ('name', ), - 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), - 'fetch_database_properties': ('environment', ), - 'get_environment': ('name', ), - 'get_user_workloads_config_map': ('name', ), - 'get_user_workloads_secret': ('name', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), - 'list_user_workloads_config_maps': ('parent', 'page_size', 'page_token', ), - 'list_user_workloads_secrets': ('parent', 'page_size', 'page_token', ), - 'list_workloads': ('parent', 'page_size', 'page_token', 'filter', ), - 'load_snapshot': ('environment', 'snapshot_path', 'skip_pypi_packages_installation', 'skip_environment_variables_setting', 'skip_airflow_overrides_setting', 'skip_gcs_data_copying', ), - 'poll_airflow_command': ('environment', 'execution_id', 'pod', 'pod_namespace', 'next_line_number', ), - 'save_snapshot': ('environment', 'snapshot_location', ), - 'stop_airflow_command': ('environment', 'execution_id', 'pod', 'pod_namespace', 'force', ), - 'update_environment': ('name', 'environment', 'update_mask', ), - 'update_user_workloads_config_map': ('user_workloads_config_map', ), - 'update_user_workloads_secret': ('user_workloads_secret', ), - } - - 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=serviceCallTransformer(), -): - """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 service 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-orchestration-airflow/v1/setup.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/setup.py deleted file mode 100644 index 49491dce0096..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow' - - -description = "Google Cloud Orchestration Airflow API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/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.0,!=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.0,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0", - "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", - "protobuf>=3.20.2,<7.0.0,!=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-orchestration-airflow" - -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-orchestration-airflow/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.7.txt deleted file mode 100644 index a77f12bc13e4..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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.0", -# 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-orchestration-airflow/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/tests/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/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-orchestration-airflow/v1/tests/unit/gapic/service_v1/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_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-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py deleted file mode 100644 index 06d721386bd7..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py +++ /dev/null @@ -1,17371 +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.orchestration.airflow.service_v1.services.environments import EnvironmentsAsyncClient -from google.cloud.orchestration.airflow.service_v1.services.environments import EnvironmentsClient -from google.cloud.orchestration.airflow.service_v1.services.environments import pagers -from google.cloud.orchestration.airflow.service_v1.services.environments import transports -from google.cloud.orchestration.airflow.service_v1.types import environments -from google.cloud.orchestration.airflow.service_v1.types import operations -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 - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) - - -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 EnvironmentsClient._get_default_mtls_endpoint(None) is None - assert EnvironmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert EnvironmentsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - EnvironmentsClient._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 EnvironmentsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert EnvironmentsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - EnvironmentsClient._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 EnvironmentsClient._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 EnvironmentsClient._get_client_cert_source(None, False) is None - assert EnvironmentsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert EnvironmentsClient._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 EnvironmentsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert EnvironmentsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = EnvironmentsClient._DEFAULT_UNIVERSE - default_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert EnvironmentsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert EnvironmentsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "always") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - assert EnvironmentsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - assert EnvironmentsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - EnvironmentsClient._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 EnvironmentsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert EnvironmentsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert EnvironmentsClient._get_universe_domain(None, None) == EnvironmentsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - EnvironmentsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) -def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): - cred = mock.Mock(["get_cred_info"]) - cred.get_cred_info = mock.Mock(return_value=cred_info_json) - client = EnvironmentsClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401,403,404,500]) -def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): - cred = mock.Mock([]) - assert not hasattr(cred, "get_cred_info") - client = EnvironmentsClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -@pytest.mark.parametrize("client_class,transport_name", [ - (EnvironmentsClient, "grpc"), - (EnvironmentsAsyncClient, "grpc_asyncio"), - (EnvironmentsClient, "rest"), -]) -def test_environments_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 == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://composer.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EnvironmentsGrpcTransport, "grpc"), - (transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EnvironmentsRestTransport, "rest"), -]) -def test_environments_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", [ - (EnvironmentsClient, "grpc"), - (EnvironmentsAsyncClient, "grpc_asyncio"), - (EnvironmentsClient, "rest"), -]) -def test_environments_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 == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://composer.googleapis.com' - ) - - -def test_environments_client_get_transport_class(): - transport = EnvironmentsClient.get_transport_class() - available_transports = [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsRestTransport, - ] - assert transport in available_transports - - transport = EnvironmentsClient.get_transport_class("grpc") - assert transport == transports.EnvironmentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), -]) -@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) -def test_environments_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(EnvironmentsClient, '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(EnvironmentsClient, '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", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "true"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "false"), -]) -@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_environments_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", [ - EnvironmentsClient, EnvironmentsAsyncClient -]) -@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) -def test_environments_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", [ - EnvironmentsClient, EnvironmentsAsyncClient -]) -@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) -def test_environments_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = EnvironmentsClient._DEFAULT_UNIVERSE - default_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EnvironmentsClient._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", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), -]) -def test_environments_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", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", None), -]) -def test_environments_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_environments_client_client_options_from_dict(): - with mock.patch('google.cloud.orchestration.airflow.service_v1.services.environments.transports.EnvironmentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EnvironmentsClient( - 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", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_environments_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( - "composer.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="composer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateEnvironmentRequest, - dict, -]) -def test_create_environment(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.CreateEnvironmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_environment_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 = EnvironmentsClient( - 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 = environments.CreateEnvironmentRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_environment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateEnvironmentRequest( - parent='parent_value', - ) - -def test_create_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - request = {} - client.create_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( - 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_environment 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_environment] = mock_rpc - - request = {} - await client.create_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.CreateEnvironmentRequest): - client = EnvironmentsAsyncClient( - 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_environment), - '__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_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.CreateEnvironmentRequest() - 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_environment_async_from_dict(): - await test_create_environment_async(request_type=dict) - -def test_create_environment_field_headers(): - client = EnvironmentsClient( - 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 = environments.CreateEnvironmentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_environment(request) - - # Establish that the 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_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.CreateEnvironmentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_environment(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_environment_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__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_environment( - parent='parent_value', - environment=environments.Environment(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].environment - mock_val = environments.Environment(name='name_value') - assert arg == mock_val - - -def test_create_environment_flattened_error(): - client = EnvironmentsClient( - 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_environment( - environments.CreateEnvironmentRequest(), - parent='parent_value', - environment=environments.Environment(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_environment_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__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_environment( - parent='parent_value', - environment=environments.Environment(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].environment - mock_val = environments.Environment(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_environment_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_environment( - environments.CreateEnvironmentRequest(), - parent='parent_value', - environment=environments.Environment(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetEnvironmentRequest, - dict, -]) -def test_get_environment(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.Environment( - name='name_value', - uuid='uuid_value', - state=environments.Environment.State.CREATING, - satisfies_pzs=True, - satisfies_pzi=True, - ) - response = client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.GetEnvironmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.Environment) - assert response.name == 'name_value' - assert response.uuid == 'uuid_value' - assert response.state == environments.Environment.State.CREATING - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - - -def test_get_environment_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 = EnvironmentsClient( - 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 = environments.GetEnvironmentRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_environment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetEnvironmentRequest( - name='name_value', - ) - -def test_get_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - request = {} - client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_environment(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_environment_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 = EnvironmentsAsyncClient( - 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_environment 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_environment] = mock_rpc - - request = {} - await client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.GetEnvironmentRequest): - client = EnvironmentsAsyncClient( - 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_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment( - name='name_value', - uuid='uuid_value', - state=environments.Environment.State.CREATING, - satisfies_pzs=True, - satisfies_pzi=True, - )) - response = await client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.GetEnvironmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.Environment) - assert response.name == 'name_value' - assert response.uuid == 'uuid_value' - assert response.state == environments.Environment.State.CREATING - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - - -@pytest.mark.asyncio -async def test_get_environment_async_from_dict(): - await test_get_environment_async(request_type=dict) - -def test_get_environment_field_headers(): - client = EnvironmentsClient( - 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 = environments.GetEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value = environments.Environment() - client.get_environment(request) - - # Establish that the 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_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.GetEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment()) - await client.get_environment(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_environment_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.Environment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_environment( - 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_environment_flattened_error(): - client = EnvironmentsClient( - 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_environment( - environments.GetEnvironmentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_environment_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.Environment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_environment( - 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_environment_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_environment( - environments.GetEnvironmentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListEnvironmentsRequest, - dict, -]) -def test_list_environments(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListEnvironmentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.ListEnvironmentsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_environments_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 = EnvironmentsClient( - 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 = environments.ListEnvironmentsRequest( - 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_environments), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_environments(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListEnvironmentsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_environments_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 = EnvironmentsClient( - 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_environments 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_environments] = mock_rpc - request = {} - client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_environments(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_environments_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 = EnvironmentsAsyncClient( - 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_environments 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_environments] = mock_rpc - - request = {} - await client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_environments(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_environments_async(transport: str = 'grpc_asyncio', request_type=environments.ListEnvironmentsRequest): - client = EnvironmentsAsyncClient( - 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_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.ListEnvironmentsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_environments_async_from_dict(): - await test_list_environments_async(request_type=dict) - -def test_list_environments_field_headers(): - client = EnvironmentsClient( - 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 = environments.ListEnvironmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - call.return_value = environments.ListEnvironmentsResponse() - client.list_environments(request) - - # Establish that the 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_environments_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.ListEnvironmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse()) - await client.list_environments(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_environments_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListEnvironmentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_environments( - 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_environments_flattened_error(): - client = EnvironmentsClient( - 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_environments( - environments.ListEnvironmentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_environments_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListEnvironmentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_environments( - 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_environments_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_environments( - environments.ListEnvironmentsRequest(), - parent='parent_value', - ) - - -def test_list_environments_pager(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_environments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - environments.Environment(), - ], - next_page_token='abc', - ), - environments.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - ], - next_page_token='ghi', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_environments(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, environments.Environment) - for i in results) -def test_list_environments_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_environments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - environments.Environment(), - ], - next_page_token='abc', - ), - environments.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - ], - next_page_token='ghi', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_environments(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_environments_async_pager(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - environments.Environment(), - ], - next_page_token='abc', - ), - environments.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - ], - next_page_token='ghi', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_environments(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, environments.Environment) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_environments_async_pages(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - environments.Environment(), - ], - next_page_token='abc', - ), - environments.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - ], - next_page_token='ghi', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - ], - ), - 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_environments(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", [ - environments.UpdateEnvironmentRequest, - dict, -]) -def test_update_environment(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.UpdateEnvironmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_environment_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 = EnvironmentsClient( - 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 = environments.UpdateEnvironmentRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_environment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateEnvironmentRequest( - name='name_value', - ) - -def test_update_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - request = {} - client.update_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( - 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_environment 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_environment] = mock_rpc - - request = {} - await client.update_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateEnvironmentRequest): - client = EnvironmentsAsyncClient( - 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_environment), - '__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_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.UpdateEnvironmentRequest() - 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_environment_async_from_dict(): - await test_update_environment_async(request_type=dict) - -def test_update_environment_field_headers(): - client = EnvironmentsClient( - 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 = environments.UpdateEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.UpdateEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_update_environment_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__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_environment( - name='name_value', - environment=environments.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].environment - mock_val = environments.Environment(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_environment_flattened_error(): - client = EnvironmentsClient( - 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_environment( - environments.UpdateEnvironmentRequest(), - name='name_value', - environment=environments.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_environment_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__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_environment( - name='name_value', - environment=environments.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].environment - mock_val = environments.Environment(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_environment_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_environment( - environments.UpdateEnvironmentRequest(), - name='name_value', - environment=environments.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteEnvironmentRequest, - dict, -]) -def test_delete_environment(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.DeleteEnvironmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_environment_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 = EnvironmentsClient( - 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 = environments.DeleteEnvironmentRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_environment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteEnvironmentRequest( - name='name_value', - ) - -def test_delete_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - request = {} - client.delete_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( - 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_environment 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_environment] = mock_rpc - - request = {} - await client.delete_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteEnvironmentRequest): - client = EnvironmentsAsyncClient( - 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_environment), - '__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_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.DeleteEnvironmentRequest() - 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_environment_async_from_dict(): - await test_delete_environment_async(request_type=dict) - -def test_delete_environment_field_headers(): - client = EnvironmentsClient( - 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 = environments.DeleteEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_environment(request) - - # Establish that the 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_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.DeleteEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_environment(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_environment_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__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_environment( - 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_environment_flattened_error(): - client = EnvironmentsClient( - 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_environment( - environments.DeleteEnvironmentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_environment_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__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_environment( - 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_environment_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_environment( - environments.DeleteEnvironmentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ExecuteAirflowCommandRequest, - dict, -]) -def test_execute_airflow_command(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.execute_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ExecuteAirflowCommandResponse( - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - error='error_value', - ) - response = client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.ExecuteAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.ExecuteAirflowCommandResponse) - assert response.execution_id == 'execution_id_value' - assert response.pod == 'pod_value' - assert response.pod_namespace == 'pod_namespace_value' - assert response.error == 'error_value' - - -def test_execute_airflow_command_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 = EnvironmentsClient( - 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 = environments.ExecuteAirflowCommandRequest( - environment='environment_value', - command='command_value', - subcommand='subcommand_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.execute_airflow_command(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ExecuteAirflowCommandRequest( - environment='environment_value', - command='command_value', - subcommand='subcommand_value', - ) - -def test_execute_airflow_command_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 = EnvironmentsClient( - 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc - request = {} - client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.execute_airflow_command(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_execute_airflow_command_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 = EnvironmentsAsyncClient( - 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc - - request = {} - await client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.execute_airflow_command(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_execute_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.ExecuteAirflowCommandRequest): - client = EnvironmentsAsyncClient( - 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.execute_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse( - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - error='error_value', - )) - response = await client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.ExecuteAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.ExecuteAirflowCommandResponse) - assert response.execution_id == 'execution_id_value' - assert response.pod == 'pod_value' - assert response.pod_namespace == 'pod_namespace_value' - assert response.error == 'error_value' - - -@pytest.mark.asyncio -async def test_execute_airflow_command_async_from_dict(): - await test_execute_airflow_command_async(request_type=dict) - -def test_execute_airflow_command_field_headers(): - client = EnvironmentsClient( - 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 = environments.ExecuteAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - call.return_value = environments.ExecuteAirflowCommandResponse() - client.execute_airflow_command(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_execute_airflow_command_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.ExecuteAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse()) - await client.execute_airflow_command(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.StopAirflowCommandRequest, - dict, -]) -def test_stop_airflow_command(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.stop_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.StopAirflowCommandResponse( - is_done=True, - output=['output_value'], - ) - response = client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.StopAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.StopAirflowCommandResponse) - assert response.is_done is True - assert response.output == ['output_value'] - - -def test_stop_airflow_command_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 = EnvironmentsClient( - 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 = environments.StopAirflowCommandRequest( - environment='environment_value', - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.stop_airflow_command(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.StopAirflowCommandRequest( - environment='environment_value', - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - ) - -def test_stop_airflow_command_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 = EnvironmentsClient( - 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc - request = {} - client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stop_airflow_command(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_stop_airflow_command_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 = EnvironmentsAsyncClient( - 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc - - request = {} - await client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.stop_airflow_command(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_stop_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.StopAirflowCommandRequest): - client = EnvironmentsAsyncClient( - 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.stop_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse( - is_done=True, - output=['output_value'], - )) - response = await client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.StopAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.StopAirflowCommandResponse) - assert response.is_done is True - assert response.output == ['output_value'] - - -@pytest.mark.asyncio -async def test_stop_airflow_command_async_from_dict(): - await test_stop_airflow_command_async(request_type=dict) - -def test_stop_airflow_command_field_headers(): - client = EnvironmentsClient( - 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 = environments.StopAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - call.return_value = environments.StopAirflowCommandResponse() - client.stop_airflow_command(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_stop_airflow_command_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.StopAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse()) - await client.stop_airflow_command(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.PollAirflowCommandRequest, - dict, -]) -def test_poll_airflow_command(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.poll_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.PollAirflowCommandResponse( - output_end=True, - ) - response = client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.PollAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.PollAirflowCommandResponse) - assert response.output_end is True - - -def test_poll_airflow_command_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 = EnvironmentsClient( - 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 = environments.PollAirflowCommandRequest( - environment='environment_value', - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.poll_airflow_command(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.PollAirflowCommandRequest( - environment='environment_value', - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - ) - -def test_poll_airflow_command_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 = EnvironmentsClient( - 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc - request = {} - client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.poll_airflow_command(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_poll_airflow_command_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 = EnvironmentsAsyncClient( - 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc - - request = {} - await client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.poll_airflow_command(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_poll_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.PollAirflowCommandRequest): - client = EnvironmentsAsyncClient( - 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.poll_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse( - output_end=True, - )) - response = await client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.PollAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.PollAirflowCommandResponse) - assert response.output_end is True - - -@pytest.mark.asyncio -async def test_poll_airflow_command_async_from_dict(): - await test_poll_airflow_command_async(request_type=dict) - -def test_poll_airflow_command_field_headers(): - client = EnvironmentsClient( - 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 = environments.PollAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - call.return_value = environments.PollAirflowCommandResponse() - client.poll_airflow_command(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_poll_airflow_command_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.PollAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse()) - await client.poll_airflow_command(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.ListWorkloadsRequest, - dict, -]) -def test_list_workloads(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_workloads), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListWorkloadsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.ListWorkloadsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkloadsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_workloads_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 = EnvironmentsClient( - 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 = environments.ListWorkloadsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workloads(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListWorkloadsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_workloads_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 = EnvironmentsClient( - 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_workloads 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_workloads] = mock_rpc - request = {} - client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workloads(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_workloads_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 = EnvironmentsAsyncClient( - 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_workloads 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_workloads] = mock_rpc - - request = {} - await client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_workloads(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_workloads_async(transport: str = 'grpc_asyncio', request_type=environments.ListWorkloadsRequest): - client = EnvironmentsAsyncClient( - 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_workloads), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.ListWorkloadsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkloadsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_workloads_async_from_dict(): - await test_list_workloads_async(request_type=dict) - -def test_list_workloads_field_headers(): - client = EnvironmentsClient( - 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 = environments.ListWorkloadsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - call.return_value = environments.ListWorkloadsResponse() - client.list_workloads(request) - - # Establish that the 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_workloads_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.ListWorkloadsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse()) - await client.list_workloads(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_workloads_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListWorkloadsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workloads( - 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_workloads_flattened_error(): - client = EnvironmentsClient( - 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_workloads( - environments.ListWorkloadsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workloads_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListWorkloadsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workloads( - 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_workloads_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_workloads( - environments.ListWorkloadsRequest(), - parent='parent_value', - ) - - -def test_list_workloads_pager(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_workloads), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='abc', - ), - environments.ListWorkloadsResponse( - workloads=[], - next_page_token='def', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='ghi', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workloads(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, environments.ListWorkloadsResponse.ComposerWorkload) - for i in results) -def test_list_workloads_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_workloads), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='abc', - ), - environments.ListWorkloadsResponse( - workloads=[], - next_page_token='def', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='ghi', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workloads(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_workloads_async_pager(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='abc', - ), - environments.ListWorkloadsResponse( - workloads=[], - next_page_token='def', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='ghi', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workloads(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, environments.ListWorkloadsResponse.ComposerWorkload) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workloads_async_pages(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='abc', - ), - environments.ListWorkloadsResponse( - workloads=[], - next_page_token='def', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='ghi', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - ), - 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_workloads(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", [ - environments.CheckUpgradeRequest, - dict, -]) -def test_check_upgrade(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.check_upgrade), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.check_upgrade(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.CheckUpgradeRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_check_upgrade_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 = EnvironmentsClient( - 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 = environments.CheckUpgradeRequest( - environment='environment_value', - image_version='image_version_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.check_upgrade(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CheckUpgradeRequest( - environment='environment_value', - image_version='image_version_value', - ) - -def test_check_upgrade_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 = EnvironmentsClient( - 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.check_upgrade 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.check_upgrade] = mock_rpc - request = {} - client.check_upgrade(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.check_upgrade(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_check_upgrade_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 = EnvironmentsAsyncClient( - 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.check_upgrade 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.check_upgrade] = mock_rpc - - request = {} - await client.check_upgrade(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.check_upgrade(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_check_upgrade_async(transport: str = 'grpc_asyncio', request_type=environments.CheckUpgradeRequest): - client = EnvironmentsAsyncClient( - 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.check_upgrade), - '__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.check_upgrade(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.CheckUpgradeRequest() - 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_check_upgrade_async_from_dict(): - await test_check_upgrade_async(request_type=dict) - -def test_check_upgrade_field_headers(): - client = EnvironmentsClient( - 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 = environments.CheckUpgradeRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.check_upgrade(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_check_upgrade_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.CheckUpgradeRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.check_upgrade(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsSecretRequest, - dict, -]) -def test_create_user_workloads_secret(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret( - name='name_value', - ) - response = client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.CreateUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -def test_create_user_workloads_secret_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 = EnvironmentsClient( - 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 = environments.CreateUserWorkloadsSecretRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_user_workloads_secret(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsSecretRequest( - parent='parent_value', - ) - -def test_create_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - request = {} - client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - await client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.CreateUserWorkloadsSecretRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - response = await client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.CreateUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_user_workloads_secret_async_from_dict(): - await test_create_user_workloads_secret_async(request_type=dict) - -def test_create_user_workloads_secret_field_headers(): - client = EnvironmentsClient( - 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 = environments.CreateUserWorkloadsSecretRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.create_user_workloads_secret(request) - - # Establish that the 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_user_workloads_secret_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.CreateUserWorkloadsSecretRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - await client.create_user_workloads_secret(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_user_workloads_secret_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_user_workloads_secret( - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].user_workloads_secret - mock_val = environments.UserWorkloadsSecret(name='name_value') - assert arg == mock_val - - -def test_create_user_workloads_secret_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.CreateUserWorkloadsSecretRequest(), - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_user_workloads_secret_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_user_workloads_secret( - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].user_workloads_secret - mock_val = environments.UserWorkloadsSecret(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_user_workloads_secret_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret( - environments.CreateUserWorkloadsSecretRequest(), - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsSecretRequest, - dict, -]) -def test_get_user_workloads_secret(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret( - name='name_value', - ) - response = client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.GetUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -def test_get_user_workloads_secret_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 = EnvironmentsClient( - 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 = environments.GetUserWorkloadsSecretRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_user_workloads_secret(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsSecretRequest( - name='name_value', - ) - -def test_get_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - request = {} - client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - await client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.GetUserWorkloadsSecretRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - response = await client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.GetUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_user_workloads_secret_async_from_dict(): - await test_get_user_workloads_secret_async(request_type=dict) - -def test_get_user_workloads_secret_field_headers(): - client = EnvironmentsClient( - 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 = environments.GetUserWorkloadsSecretRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.get_user_workloads_secret(request) - - # Establish that the 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_user_workloads_secret_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.GetUserWorkloadsSecretRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - await client.get_user_workloads_secret(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_user_workloads_secret_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_user_workloads_secret( - 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_user_workloads_secret_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.GetUserWorkloadsSecretRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_user_workloads_secret_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_user_workloads_secret( - 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_user_workloads_secret_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret( - environments.GetUserWorkloadsSecretRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsSecretsRequest, - dict, -]) -def test_list_user_workloads_secrets(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_secrets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsSecretsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.ListUserWorkloadsSecretsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsSecretsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_user_workloads_secrets_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 = EnvironmentsClient( - 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 = environments.ListUserWorkloadsSecretsRequest( - 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_user_workloads_secrets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_user_workloads_secrets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsSecretsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_user_workloads_secrets_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 = EnvironmentsClient( - 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc - request = {} - client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_user_workloads_secrets(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_user_workloads_secrets_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 = EnvironmentsAsyncClient( - 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc - - request = {} - await client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_user_workloads_secrets(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_user_workloads_secrets_async(transport: str = 'grpc_asyncio', request_type=environments.ListUserWorkloadsSecretsRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_secrets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.ListUserWorkloadsSecretsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsSecretsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_user_workloads_secrets_async_from_dict(): - await test_list_user_workloads_secrets_async(request_type=dict) - -def test_list_user_workloads_secrets_field_headers(): - client = EnvironmentsClient( - 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 = environments.ListUserWorkloadsSecretsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - call.return_value = environments.ListUserWorkloadsSecretsResponse() - client.list_user_workloads_secrets(request) - - # Establish that the 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_user_workloads_secrets_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.ListUserWorkloadsSecretsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse()) - await client.list_user_workloads_secrets(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_user_workloads_secrets_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsSecretsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_user_workloads_secrets( - 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_user_workloads_secrets_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_secrets( - environments.ListUserWorkloadsSecretsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_user_workloads_secrets_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsSecretsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_user_workloads_secrets( - 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_user_workloads_secrets_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_secrets( - environments.ListUserWorkloadsSecretsRequest(), - parent='parent_value', - ) - - -def test_list_user_workloads_secrets_pager(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_user_workloads_secrets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[], - next_page_token='def', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_user_workloads_secrets(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, environments.UserWorkloadsSecret) - for i in results) -def test_list_user_workloads_secrets_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_user_workloads_secrets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[], - next_page_token='def', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - ), - RuntimeError, - ) - pages = list(client.list_user_workloads_secrets(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_user_workloads_secrets_async_pager(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[], - next_page_token='def', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_user_workloads_secrets(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, environments.UserWorkloadsSecret) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_user_workloads_secrets_async_pages(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[], - next_page_token='def', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - ), - 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_user_workloads_secrets(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", [ - environments.UpdateUserWorkloadsSecretRequest, - dict, -]) -def test_update_user_workloads_secret(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret( - name='name_value', - ) - response = client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.UpdateUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -def test_update_user_workloads_secret_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 = EnvironmentsClient( - 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 = environments.UpdateUserWorkloadsSecretRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_user_workloads_secret(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsSecretRequest( - ) - -def test_update_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - request = {} - client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - await client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateUserWorkloadsSecretRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - response = await client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.UpdateUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_user_workloads_secret_async_from_dict(): - await test_update_user_workloads_secret_async(request_type=dict) - -def test_update_user_workloads_secret_field_headers(): - client = EnvironmentsClient( - 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 = environments.UpdateUserWorkloadsSecretRequest() - - request.user_workloads_secret.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.update_user_workloads_secret(request) - - # Establish that the 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', - 'user_workloads_secret.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_user_workloads_secret_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.UpdateUserWorkloadsSecretRequest() - - request.user_workloads_secret.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - await client.update_user_workloads_secret(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', - 'user_workloads_secret.name=name_value', - ) in kw['metadata'] - - -def test_update_user_workloads_secret_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_user_workloads_secret( - user_workloads_secret=environments.UserWorkloadsSecret(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].user_workloads_secret - mock_val = environments.UserWorkloadsSecret(name='name_value') - assert arg == mock_val - - -def test_update_user_workloads_secret_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.UpdateUserWorkloadsSecretRequest(), - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_user_workloads_secret_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_user_workloads_secret( - user_workloads_secret=environments.UserWorkloadsSecret(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].user_workloads_secret - mock_val = environments.UserWorkloadsSecret(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_user_workloads_secret_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret( - environments.UpdateUserWorkloadsSecretRequest(), - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsSecretRequest, - dict, -]) -def test_delete_user_workloads_secret(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.DeleteUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_user_workloads_secret_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 = EnvironmentsClient( - 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 = environments.DeleteUserWorkloadsSecretRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_user_workloads_secret(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsSecretRequest( - name='name_value', - ) - -def test_delete_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - request = {} - client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - await client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteUserWorkloadsSecretRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.DeleteUserWorkloadsSecretRequest() - 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_user_workloads_secret_async_from_dict(): - await test_delete_user_workloads_secret_async(request_type=dict) - -def test_delete_user_workloads_secret_field_headers(): - client = EnvironmentsClient( - 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 = environments.DeleteUserWorkloadsSecretRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - call.return_value = None - client.delete_user_workloads_secret(request) - - # Establish that the 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_user_workloads_secret_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.DeleteUserWorkloadsSecretRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user_workloads_secret(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_user_workloads_secret_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_user_workloads_secret( - 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_user_workloads_secret_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.DeleteUserWorkloadsSecretRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_user_workloads_secret_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_user_workloads_secret( - 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_user_workloads_secret_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret( - environments.DeleteUserWorkloadsSecretRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsConfigMapRequest, - dict, -]) -def test_create_user_workloads_config_map(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap( - name='name_value', - ) - response = client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.CreateUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -def test_create_user_workloads_config_map_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 = EnvironmentsClient( - 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 = environments.CreateUserWorkloadsConfigMapRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_user_workloads_config_map(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsConfigMapRequest( - parent='parent_value', - ) - -def test_create_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - request = {} - client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - await client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.CreateUserWorkloadsConfigMapRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - response = await client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.CreateUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_user_workloads_config_map_async_from_dict(): - await test_create_user_workloads_config_map_async(request_type=dict) - -def test_create_user_workloads_config_map_field_headers(): - client = EnvironmentsClient( - 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 = environments.CreateUserWorkloadsConfigMapRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.create_user_workloads_config_map(request) - - # Establish that the 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_user_workloads_config_map_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.CreateUserWorkloadsConfigMapRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - await client.create_user_workloads_config_map(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_user_workloads_config_map_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_user_workloads_config_map( - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].user_workloads_config_map - mock_val = environments.UserWorkloadsConfigMap(name='name_value') - assert arg == mock_val - - -def test_create_user_workloads_config_map_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.CreateUserWorkloadsConfigMapRequest(), - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_user_workloads_config_map_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_user_workloads_config_map( - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].user_workloads_config_map - mock_val = environments.UserWorkloadsConfigMap(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_user_workloads_config_map_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map( - environments.CreateUserWorkloadsConfigMapRequest(), - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsConfigMapRequest, - dict, -]) -def test_get_user_workloads_config_map(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap( - name='name_value', - ) - response = client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.GetUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -def test_get_user_workloads_config_map_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 = EnvironmentsClient( - 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 = environments.GetUserWorkloadsConfigMapRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_user_workloads_config_map(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsConfigMapRequest( - name='name_value', - ) - -def test_get_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - request = {} - client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - await client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.GetUserWorkloadsConfigMapRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - response = await client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.GetUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_user_workloads_config_map_async_from_dict(): - await test_get_user_workloads_config_map_async(request_type=dict) - -def test_get_user_workloads_config_map_field_headers(): - client = EnvironmentsClient( - 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 = environments.GetUserWorkloadsConfigMapRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.get_user_workloads_config_map(request) - - # Establish that the 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_user_workloads_config_map_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.GetUserWorkloadsConfigMapRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - await client.get_user_workloads_config_map(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_user_workloads_config_map_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_user_workloads_config_map( - 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_user_workloads_config_map_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.GetUserWorkloadsConfigMapRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_user_workloads_config_map_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_user_workloads_config_map( - 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_user_workloads_config_map_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map( - environments.GetUserWorkloadsConfigMapRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsConfigMapsRequest, - dict, -]) -def test_list_user_workloads_config_maps(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_config_maps), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsConfigMapsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.ListUserWorkloadsConfigMapsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsConfigMapsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_user_workloads_config_maps_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 = EnvironmentsClient( - 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 = environments.ListUserWorkloadsConfigMapsRequest( - 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_user_workloads_config_maps), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_user_workloads_config_maps(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsConfigMapsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_user_workloads_config_maps_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 = EnvironmentsClient( - 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc - request = {} - client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_user_workloads_config_maps(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_user_workloads_config_maps_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 = EnvironmentsAsyncClient( - 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc - - request = {} - await client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_user_workloads_config_maps(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_user_workloads_config_maps_async(transport: str = 'grpc_asyncio', request_type=environments.ListUserWorkloadsConfigMapsRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_maps), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.ListUserWorkloadsConfigMapsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsConfigMapsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_user_workloads_config_maps_async_from_dict(): - await test_list_user_workloads_config_maps_async(request_type=dict) - -def test_list_user_workloads_config_maps_field_headers(): - client = EnvironmentsClient( - 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 = environments.ListUserWorkloadsConfigMapsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - call.return_value = environments.ListUserWorkloadsConfigMapsResponse() - client.list_user_workloads_config_maps(request) - - # Establish that the 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_user_workloads_config_maps_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.ListUserWorkloadsConfigMapsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse()) - await client.list_user_workloads_config_maps(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_user_workloads_config_maps_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsConfigMapsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_user_workloads_config_maps( - 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_user_workloads_config_maps_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_config_maps( - environments.ListUserWorkloadsConfigMapsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_user_workloads_config_maps_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsConfigMapsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_user_workloads_config_maps( - 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_user_workloads_config_maps_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_maps( - environments.ListUserWorkloadsConfigMapsRequest(), - parent='parent_value', - ) - - -def test_list_user_workloads_config_maps_pager(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_user_workloads_config_maps), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[], - next_page_token='def', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_user_workloads_config_maps(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, environments.UserWorkloadsConfigMap) - for i in results) -def test_list_user_workloads_config_maps_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_user_workloads_config_maps), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[], - next_page_token='def', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - ), - RuntimeError, - ) - pages = list(client.list_user_workloads_config_maps(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_user_workloads_config_maps_async_pager(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[], - next_page_token='def', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_user_workloads_config_maps(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, environments.UserWorkloadsConfigMap) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_user_workloads_config_maps_async_pages(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[], - next_page_token='def', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - ), - 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_user_workloads_config_maps(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", [ - environments.UpdateUserWorkloadsConfigMapRequest, - dict, -]) -def test_update_user_workloads_config_map(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap( - name='name_value', - ) - response = client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.UpdateUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -def test_update_user_workloads_config_map_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 = EnvironmentsClient( - 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 = environments.UpdateUserWorkloadsConfigMapRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_user_workloads_config_map(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest( - ) - -def test_update_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - request = {} - client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - await client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateUserWorkloadsConfigMapRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - response = await client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.UpdateUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_user_workloads_config_map_async_from_dict(): - await test_update_user_workloads_config_map_async(request_type=dict) - -def test_update_user_workloads_config_map_field_headers(): - client = EnvironmentsClient( - 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 = environments.UpdateUserWorkloadsConfigMapRequest() - - request.user_workloads_config_map.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.update_user_workloads_config_map(request) - - # Establish that the 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', - 'user_workloads_config_map.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_user_workloads_config_map_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.UpdateUserWorkloadsConfigMapRequest() - - request.user_workloads_config_map.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - await client.update_user_workloads_config_map(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', - 'user_workloads_config_map.name=name_value', - ) in kw['metadata'] - - -def test_update_user_workloads_config_map_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_user_workloads_config_map( - user_workloads_config_map=environments.UserWorkloadsConfigMap(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].user_workloads_config_map - mock_val = environments.UserWorkloadsConfigMap(name='name_value') - assert arg == mock_val - - -def test_update_user_workloads_config_map_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.UpdateUserWorkloadsConfigMapRequest(), - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_user_workloads_config_map_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_user_workloads_config_map( - user_workloads_config_map=environments.UserWorkloadsConfigMap(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].user_workloads_config_map - mock_val = environments.UserWorkloadsConfigMap(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_user_workloads_config_map_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map( - environments.UpdateUserWorkloadsConfigMapRequest(), - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsConfigMapRequest, - dict, -]) -def test_delete_user_workloads_config_map(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.DeleteUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_user_workloads_config_map_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 = EnvironmentsClient( - 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 = environments.DeleteUserWorkloadsConfigMapRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_user_workloads_config_map(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest( - name='name_value', - ) - -def test_delete_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - request = {} - client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - await client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteUserWorkloadsConfigMapRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.DeleteUserWorkloadsConfigMapRequest() - 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_user_workloads_config_map_async_from_dict(): - await test_delete_user_workloads_config_map_async(request_type=dict) - -def test_delete_user_workloads_config_map_field_headers(): - client = EnvironmentsClient( - 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 = environments.DeleteUserWorkloadsConfigMapRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - call.return_value = None - client.delete_user_workloads_config_map(request) - - # Establish that the 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_user_workloads_config_map_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.DeleteUserWorkloadsConfigMapRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user_workloads_config_map(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_user_workloads_config_map_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_user_workloads_config_map( - 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_user_workloads_config_map_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.DeleteUserWorkloadsConfigMapRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_user_workloads_config_map_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_user_workloads_config_map( - 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_user_workloads_config_map_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map( - environments.DeleteUserWorkloadsConfigMapRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.SaveSnapshotRequest, - dict, -]) -def test_save_snapshot(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.save_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.save_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.SaveSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_save_snapshot_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 = EnvironmentsClient( - 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 = environments.SaveSnapshotRequest( - environment='environment_value', - snapshot_location='snapshot_location_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.save_snapshot(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.SaveSnapshotRequest( - environment='environment_value', - snapshot_location='snapshot_location_value', - ) - -def test_save_snapshot_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 = EnvironmentsClient( - 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.save_snapshot 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.save_snapshot] = mock_rpc - request = {} - client.save_snapshot(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.save_snapshot(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_save_snapshot_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 = EnvironmentsAsyncClient( - 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.save_snapshot 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.save_snapshot] = mock_rpc - - request = {} - await client.save_snapshot(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.save_snapshot(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_save_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.SaveSnapshotRequest): - client = EnvironmentsAsyncClient( - 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.save_snapshot), - '__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.save_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.SaveSnapshotRequest() - 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_save_snapshot_async_from_dict(): - await test_save_snapshot_async(request_type=dict) - -def test_save_snapshot_field_headers(): - client = EnvironmentsClient( - 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 = environments.SaveSnapshotRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.save_snapshot(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_save_snapshot_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.SaveSnapshotRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.save_snapshot(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.LoadSnapshotRequest, - dict, -]) -def test_load_snapshot(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.load_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.load_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.LoadSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_load_snapshot_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 = EnvironmentsClient( - 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 = environments.LoadSnapshotRequest( - environment='environment_value', - snapshot_path='snapshot_path_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.load_snapshot(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.LoadSnapshotRequest( - environment='environment_value', - snapshot_path='snapshot_path_value', - ) - -def test_load_snapshot_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 = EnvironmentsClient( - 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.load_snapshot 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.load_snapshot] = mock_rpc - request = {} - client.load_snapshot(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.load_snapshot(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_load_snapshot_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 = EnvironmentsAsyncClient( - 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.load_snapshot 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.load_snapshot] = mock_rpc - - request = {} - await client.load_snapshot(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.load_snapshot(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_load_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.LoadSnapshotRequest): - client = EnvironmentsAsyncClient( - 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.load_snapshot), - '__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.load_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.LoadSnapshotRequest() - 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_load_snapshot_async_from_dict(): - await test_load_snapshot_async(request_type=dict) - -def test_load_snapshot_field_headers(): - client = EnvironmentsClient( - 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 = environments.LoadSnapshotRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.load_snapshot(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_load_snapshot_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.LoadSnapshotRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.load_snapshot(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.DatabaseFailoverRequest, - dict, -]) -def test_database_failover(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.database_failover), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.database_failover(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.DatabaseFailoverRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_database_failover_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 = EnvironmentsClient( - 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 = environments.DatabaseFailoverRequest( - environment='environment_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.database_failover(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DatabaseFailoverRequest( - environment='environment_value', - ) - -def test_database_failover_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 = EnvironmentsClient( - 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.database_failover 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.database_failover] = mock_rpc - request = {} - client.database_failover(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.database_failover(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_database_failover_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 = EnvironmentsAsyncClient( - 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.database_failover 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.database_failover] = mock_rpc - - request = {} - await client.database_failover(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.database_failover(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_database_failover_async(transport: str = 'grpc_asyncio', request_type=environments.DatabaseFailoverRequest): - client = EnvironmentsAsyncClient( - 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.database_failover), - '__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.database_failover(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.DatabaseFailoverRequest() - 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_database_failover_async_from_dict(): - await test_database_failover_async(request_type=dict) - -def test_database_failover_field_headers(): - client = EnvironmentsClient( - 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 = environments.DatabaseFailoverRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.database_failover(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_database_failover_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.DatabaseFailoverRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.database_failover(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.FetchDatabasePropertiesRequest, - dict, -]) -def test_fetch_database_properties(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.fetch_database_properties), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.FetchDatabasePropertiesResponse( - primary_gce_zone='primary_gce_zone_value', - secondary_gce_zone='secondary_gce_zone_value', - is_failover_replica_available=True, - ) - response = client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.FetchDatabasePropertiesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.FetchDatabasePropertiesResponse) - assert response.primary_gce_zone == 'primary_gce_zone_value' - assert response.secondary_gce_zone == 'secondary_gce_zone_value' - assert response.is_failover_replica_available is True - - -def test_fetch_database_properties_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 = EnvironmentsClient( - 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 = environments.FetchDatabasePropertiesRequest( - environment='environment_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.fetch_database_properties(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.FetchDatabasePropertiesRequest( - environment='environment_value', - ) - -def test_fetch_database_properties_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 = EnvironmentsClient( - 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc - request = {} - client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_database_properties(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_fetch_database_properties_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 = EnvironmentsAsyncClient( - 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc - - request = {} - await client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.fetch_database_properties(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_fetch_database_properties_async(transport: str = 'grpc_asyncio', request_type=environments.FetchDatabasePropertiesRequest): - client = EnvironmentsAsyncClient( - 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.fetch_database_properties), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse( - primary_gce_zone='primary_gce_zone_value', - secondary_gce_zone='secondary_gce_zone_value', - is_failover_replica_available=True, - )) - response = await client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.FetchDatabasePropertiesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.FetchDatabasePropertiesResponse) - assert response.primary_gce_zone == 'primary_gce_zone_value' - assert response.secondary_gce_zone == 'secondary_gce_zone_value' - assert response.is_failover_replica_available is True - - -@pytest.mark.asyncio -async def test_fetch_database_properties_async_from_dict(): - await test_fetch_database_properties_async(request_type=dict) - -def test_fetch_database_properties_field_headers(): - client = EnvironmentsClient( - 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 = environments.FetchDatabasePropertiesRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - call.return_value = environments.FetchDatabasePropertiesResponse() - client.fetch_database_properties(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_fetch_database_properties_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.FetchDatabasePropertiesRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse()) - await client.fetch_database_properties(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', - 'environment=environment_value', - ) in kw['metadata'] - - -def test_create_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - - request = {} - client.create_environment(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_environment(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_environment_rest_flattened(): - client = EnvironmentsClient( - 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', - environment=environments.Environment(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.create_environment(**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/*}/environments" % client.transport._host, args[1]) - - -def test_create_environment_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_environment( - environments.CreateEnvironmentRequest(), - parent='parent_value', - environment=environments.Environment(name='name_value'), - ) - - -def test_get_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - - request = {} - client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_environment(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_environment_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.Environment() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/environments/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 = environments.Environment.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_environment(**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/*/environments/*}" % client.transport._host, args[1]) - - -def test_get_environment_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_environment( - environments.GetEnvironmentRequest(), - name='name_value', - ) - - -def test_list_environments_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 = EnvironmentsClient( - 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_environments 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_environments] = mock_rpc - - request = {} - client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_environments(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_environments_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.ListEnvironmentsResponse() - - # 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 = environments.ListEnvironmentsResponse.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_environments(**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/*}/environments" % client.transport._host, args[1]) - - -def test_list_environments_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_environments( - environments.ListEnvironmentsRequest(), - parent='parent_value', - ) - - -def test_list_environments_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - 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 = ( - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - environments.Environment(), - ], - next_page_token='abc', - ), - environments.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - ], - next_page_token='ghi', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environments.ListEnvironmentsResponse.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_environments(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environments.Environment) - for i in results) - - pages = list(client.list_environments(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_update_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - - request = {} - client.update_environment(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_environment(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_environment_rest_flattened(): - client = EnvironmentsClient( - 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/environments/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - environment=environments.Environment(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_environment(**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/*/environments/*}" % client.transport._host, args[1]) - - -def test_update_environment_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_environment( - environments.UpdateEnvironmentRequest(), - name='name_value', - environment=environments.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - - request = {} - client.delete_environment(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_environment(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_environment_rest_flattened(): - client = EnvironmentsClient( - 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/environments/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_environment(**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/*/environments/*}" % client.transport._host, args[1]) - - -def test_delete_environment_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_environment( - environments.DeleteEnvironmentRequest(), - name='name_value', - ) - - -def test_execute_airflow_command_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 = EnvironmentsClient( - 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc - - request = {} - client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.execute_airflow_command(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_stop_airflow_command_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 = EnvironmentsClient( - 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc - - request = {} - client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stop_airflow_command(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_poll_airflow_command_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 = EnvironmentsClient( - 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc - - request = {} - client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.poll_airflow_command(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_workloads_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 = EnvironmentsClient( - 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_workloads 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_workloads] = mock_rpc - - request = {} - client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workloads(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_workloads_rest_required_fields(request_type=environments.ListWorkloadsRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_workloads._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_workloads._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.ListWorkloadsResponse() - # 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 = environments.ListWorkloadsResponse.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_workloads(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workloads_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workloads._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_workloads_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.ListWorkloadsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListWorkloadsResponse.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_workloads(**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/*/environments/*}/workloads" % client.transport._host, args[1]) - - -def test_list_workloads_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_workloads( - environments.ListWorkloadsRequest(), - parent='parent_value', - ) - - -def test_list_workloads_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - 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 = ( - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='abc', - ), - environments.ListWorkloadsResponse( - workloads=[], - next_page_token='def', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='ghi', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environments.ListWorkloadsResponse.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/environments/sample3'} - - pager = client.list_workloads(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environments.ListWorkloadsResponse.ComposerWorkload) - for i in results) - - pages = list(client.list_workloads(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_check_upgrade_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 = EnvironmentsClient( - 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.check_upgrade 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.check_upgrade] = mock_rpc - - request = {} - client.check_upgrade(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.check_upgrade(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_check_upgrade_rest_required_fields(request_type=environments.CheckUpgradeRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["environment"] = "" - 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()).check_upgrade._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["environment"] = 'environment_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).check_upgrade._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "environment" in jsonified_request - assert jsonified_request["environment"] == 'environment_value' - - client = EnvironmentsClient( - 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.check_upgrade(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_check_upgrade_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.check_upgrade._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("environment", ))) - - -def test_create_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.CreateUserWorkloadsSecretRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_secret._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_secret._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.UserWorkloadsSecret() - # 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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_user_workloads_secret_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_user_workloads_secret._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "userWorkloadsSecret", ))) - - -def test_create_user_workloads_secret_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsSecret() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(**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/*/environments/*}/userWorkloadsSecrets" % client.transport._host, args[1]) - - -def test_create_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.CreateUserWorkloadsSecretRequest(), - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - - -def test_get_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.GetUserWorkloadsSecretRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_secret._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_user_workloads_secret._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.UserWorkloadsSecret() - # 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 = environments.UserWorkloadsSecret.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_user_workloads_secret(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_user_workloads_secret_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_user_workloads_secret._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_user_workloads_secret_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsSecret() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = environments.UserWorkloadsSecret.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_user_workloads_secret(**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/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) - - -def test_get_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.GetUserWorkloadsSecretRequest(), - name='name_value', - ) - - -def test_list_user_workloads_secrets_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 = EnvironmentsClient( - 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc - - request = {} - client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_user_workloads_secrets(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_user_workloads_secrets_rest_required_fields(request_type=environments.ListUserWorkloadsSecretsRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_secrets._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_user_workloads_secrets._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.ListUserWorkloadsSecretsResponse() - # 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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_user_workloads_secrets_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_user_workloads_secrets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_user_workloads_secrets_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.ListUserWorkloadsSecretsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(**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/*/environments/*}/userWorkloadsSecrets" % client.transport._host, args[1]) - - -def test_list_user_workloads_secrets_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_secrets( - environments.ListUserWorkloadsSecretsRequest(), - parent='parent_value', - ) - - -def test_list_user_workloads_secrets_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - 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 = ( - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[], - next_page_token='def', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environments.ListUserWorkloadsSecretsResponse.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/environments/sample3'} - - pager = client.list_user_workloads_secrets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environments.UserWorkloadsSecret) - for i in results) - - pages = list(client.list_user_workloads_secrets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_update_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user_workloads_secret(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_user_workloads_secret_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsSecret() - - # get arguments that satisfy an http rule for this method - sample_request = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - user_workloads_secret=environments.UserWorkloadsSecret(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 = environments.UserWorkloadsSecret.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.update_user_workloads_secret(**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/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) - - -def test_update_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.UpdateUserWorkloadsSecretRequest(), - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - - -def test_delete_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.DeleteUserWorkloadsSecretRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_secret._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_user_workloads_secret._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # 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 = '' - - response_value._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_user_workloads_secret(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_user_workloads_secret_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_user_workloads_secret._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_user_workloads_secret_rest_flattened(): - client = EnvironmentsClient( - 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 = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = '' - response_value._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_user_workloads_secret(**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/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) - - -def test_delete_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.DeleteUserWorkloadsSecretRequest(), - name='name_value', - ) - - -def test_create_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.CreateUserWorkloadsConfigMapRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_config_map._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_config_map._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.UserWorkloadsConfigMap() - # 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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_user_workloads_config_map_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_user_workloads_config_map._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "userWorkloadsConfigMap", ))) - - -def test_create_user_workloads_config_map_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsConfigMap() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(**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/*/environments/*}/userWorkloadsConfigMaps" % client.transport._host, args[1]) - - -def test_create_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.CreateUserWorkloadsConfigMapRequest(), - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - - -def test_get_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.GetUserWorkloadsConfigMapRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_config_map._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_user_workloads_config_map._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.UserWorkloadsConfigMap() - # 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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_user_workloads_config_map_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_user_workloads_config_map._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_user_workloads_config_map_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsConfigMap() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(**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/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) - - -def test_get_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.GetUserWorkloadsConfigMapRequest(), - name='name_value', - ) - - -def test_list_user_workloads_config_maps_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 = EnvironmentsClient( - 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc - - request = {} - client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_user_workloads_config_maps(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_user_workloads_config_maps_rest_required_fields(request_type=environments.ListUserWorkloadsConfigMapsRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_config_maps._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_user_workloads_config_maps._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.ListUserWorkloadsConfigMapsResponse() - # 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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_user_workloads_config_maps_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_user_workloads_config_maps._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_user_workloads_config_maps_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.ListUserWorkloadsConfigMapsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(**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/*/environments/*}/userWorkloadsConfigMaps" % client.transport._host, args[1]) - - -def test_list_user_workloads_config_maps_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_config_maps( - environments.ListUserWorkloadsConfigMapsRequest(), - parent='parent_value', - ) - - -def test_list_user_workloads_config_maps_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - 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 = ( - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[], - next_page_token='def', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environments.ListUserWorkloadsConfigMapsResponse.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/environments/sample3'} - - pager = client.list_user_workloads_config_maps(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environments.UserWorkloadsConfigMap) - for i in results) - - pages = list(client.list_user_workloads_config_maps(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_update_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user_workloads_config_map(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_user_workloads_config_map_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsConfigMap() - - # get arguments that satisfy an http rule for this method - sample_request = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - user_workloads_config_map=environments.UserWorkloadsConfigMap(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 = environments.UserWorkloadsConfigMap.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.update_user_workloads_config_map(**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/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) - - -def test_update_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.UpdateUserWorkloadsConfigMapRequest(), - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - - -def test_delete_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.DeleteUserWorkloadsConfigMapRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_config_map._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_user_workloads_config_map._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # 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 = '' - - response_value._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_user_workloads_config_map(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_user_workloads_config_map_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_user_workloads_config_map._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_user_workloads_config_map_rest_flattened(): - client = EnvironmentsClient( - 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 = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = '' - response_value._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_user_workloads_config_map(**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/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) - - -def test_delete_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.DeleteUserWorkloadsConfigMapRequest(), - name='name_value', - ) - - -def test_save_snapshot_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 = EnvironmentsClient( - 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.save_snapshot 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.save_snapshot] = mock_rpc - - request = {} - client.save_snapshot(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.save_snapshot(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_load_snapshot_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 = EnvironmentsClient( - 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.load_snapshot 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.load_snapshot] = mock_rpc - - request = {} - client.load_snapshot(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.load_snapshot(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_database_failover_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 = EnvironmentsClient( - 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.database_failover 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.database_failover] = mock_rpc - - request = {} - client.database_failover(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.database_failover(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_fetch_database_properties_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 = EnvironmentsClient( - 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc - - request = {} - client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_database_properties(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_fetch_database_properties_rest_required_fields(request_type=environments.FetchDatabasePropertiesRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["environment"] = "" - 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()).fetch_database_properties._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["environment"] = 'environment_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_database_properties._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "environment" in jsonified_request - assert jsonified_request["environment"] == 'environment_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.FetchDatabasePropertiesResponse() - # 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 = environments.FetchDatabasePropertiesResponse.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.fetch_database_properties(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_fetch_database_properties_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.fetch_database_properties._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("environment", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EnvironmentsClient( - 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 = EnvironmentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EnvironmentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EnvironmentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - transports.EnvironmentsRestTransport, -]) -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 = EnvironmentsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = EnvironmentsClient( - 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_environment_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateEnvironmentRequest() - - 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_environment_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value = environments.Environment() - client.get_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetEnvironmentRequest() - - 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_environments_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - call.return_value = environments.ListEnvironmentsResponse() - client.list_environments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListEnvironmentsRequest() - - 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_environment_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateEnvironmentRequest() - - 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_environment_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteEnvironmentRequest() - - 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_execute_airflow_command_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - call.return_value = environments.ExecuteAirflowCommandResponse() - client.execute_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ExecuteAirflowCommandRequest() - - 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_stop_airflow_command_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - call.return_value = environments.StopAirflowCommandResponse() - client.stop_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.StopAirflowCommandRequest() - - 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_poll_airflow_command_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - call.return_value = environments.PollAirflowCommandResponse() - client.poll_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.PollAirflowCommandRequest() - - 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_workloads_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - call.return_value = environments.ListWorkloadsResponse() - client.list_workloads(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListWorkloadsRequest() - - 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_check_upgrade_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.check_upgrade(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CheckUpgradeRequest() - - 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_user_workloads_secret_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.create_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.get_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsSecretRequest() - - 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_user_workloads_secrets_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - call.return_value = environments.ListUserWorkloadsSecretsResponse() - client.list_user_workloads_secrets(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsSecretsRequest() - - 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_user_workloads_secret_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.update_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - call.return_value = None - client.delete_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsSecretRequest() - - 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_user_workloads_config_map_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.create_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.get_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_maps_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - call.return_value = environments.ListUserWorkloadsConfigMapsResponse() - client.list_user_workloads_config_maps(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsConfigMapsRequest() - - 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_user_workloads_config_map_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.update_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - call.return_value = None - client.delete_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsConfigMapRequest() - - 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_save_snapshot_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.save_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.SaveSnapshotRequest() - - 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_load_snapshot_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.load_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.LoadSnapshotRequest() - - 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_database_failover_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.database_failover(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DatabaseFailoverRequest() - - 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_fetch_database_properties_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - call.return_value = environments.FetchDatabasePropertiesResponse() - client.fetch_database_properties(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.FetchDatabasePropertiesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = EnvironmentsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = EnvironmentsAsyncClient( - 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_environment_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__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_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateEnvironmentRequest() - - 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_environment_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment( - name='name_value', - uuid='uuid_value', - state=environments.Environment.State.CREATING, - satisfies_pzs=True, - satisfies_pzi=True, - )) - await client.get_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetEnvironmentRequest() - - 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_environments_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse( - next_page_token='next_page_token_value', - )) - await client.list_environments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListEnvironmentsRequest() - - 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_environment_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__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_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateEnvironmentRequest() - - 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_environment_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__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_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteEnvironmentRequest() - - 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_execute_airflow_command_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse( - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - error='error_value', - )) - await client.execute_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ExecuteAirflowCommandRequest() - - 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_stop_airflow_command_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse( - is_done=True, - output=['output_value'], - )) - await client.stop_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.StopAirflowCommandRequest() - - 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_poll_airflow_command_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse( - output_end=True, - )) - await client.poll_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.PollAirflowCommandRequest() - - 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_workloads_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse( - next_page_token='next_page_token_value', - )) - await client.list_workloads(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListWorkloadsRequest() - - 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_check_upgrade_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__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.check_upgrade(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CheckUpgradeRequest() - - 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_user_workloads_secret_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - await client.create_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - await client.get_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsSecretRequest() - - 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_user_workloads_secrets_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse( - next_page_token='next_page_token_value', - )) - await client.list_user_workloads_secrets(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsSecretsRequest() - - 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_user_workloads_secret_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - await client.update_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsSecretRequest() - - 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_user_workloads_config_map_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - await client.create_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - await client.get_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_maps_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse( - next_page_token='next_page_token_value', - )) - await client.list_user_workloads_config_maps(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsConfigMapsRequest() - - 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_user_workloads_config_map_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - await client.update_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsConfigMapRequest() - - 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_save_snapshot_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__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.save_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.SaveSnapshotRequest() - - 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_load_snapshot_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__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.load_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.LoadSnapshotRequest() - - 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_database_failover_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__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.database_failover(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DatabaseFailoverRequest() - - 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_fetch_database_properties_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse( - primary_gce_zone='primary_gce_zone_value', - secondary_gce_zone='secondary_gce_zone_value', - is_failover_replica_available=True, - )) - await client.fetch_database_properties(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.FetchDatabasePropertiesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = EnvironmentsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_environment_rest_bad_request(request_type=environments.CreateEnvironmentRequest): - client = EnvironmentsClient( - 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_environment(request) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateEnvironmentRequest, - dict, -]) -def test_create_environment_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["environment"] = {'name': 'name_value', 'config': {'gke_cluster': 'gke_cluster_value', 'dag_gcs_prefix': 'dag_gcs_prefix_value', 'node_count': 1070, 'software_config': {'image_version': 'image_version_value', 'airflow_config_overrides': {}, 'pypi_packages': {}, 'env_variables': {}, 'python_version': 'python_version_value', 'scheduler_count': 1607, 'cloud_data_lineage_integration': {'enabled': True}, 'web_server_plugins_mode': 1}, 'node_config': {'location': 'location_value', 'machine_type': 'machine_type_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'disk_size_gb': 1261, 'oauth_scopes': ['oauth_scopes_value1', 'oauth_scopes_value2'], 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'ip_allocation_policy': {'use_ip_aliases': True, 'cluster_secondary_range_name': 'cluster_secondary_range_name_value', 'cluster_ipv4_cidr_block': 'cluster_ipv4_cidr_block_value', 'services_secondary_range_name': 'services_secondary_range_name_value', 'services_ipv4_cidr_block': 'services_ipv4_cidr_block_value'}, 'enable_ip_masq_agent': True, 'composer_network_attachment': 'composer_network_attachment_value', 'composer_internal_ipv4_cidr_block': 'composer_internal_ipv4_cidr_block_value'}, 'private_environment_config': {'enable_private_environment': True, 'enable_private_builds_only': True, 'private_cluster_config': {'enable_private_endpoint': True, 'master_ipv4_cidr_block': 'master_ipv4_cidr_block_value', 'master_ipv4_reserved_range': 'master_ipv4_reserved_range_value'}, 'web_server_ipv4_cidr_block': 'web_server_ipv4_cidr_block_value', 'cloud_sql_ipv4_cidr_block': 'cloud_sql_ipv4_cidr_block_value', 'web_server_ipv4_reserved_range': 'web_server_ipv4_reserved_range_value', 'cloud_composer_network_ipv4_cidr_block': 'cloud_composer_network_ipv4_cidr_block_value', 'cloud_composer_network_ipv4_reserved_range': 'cloud_composer_network_ipv4_reserved_range_value', 'enable_privately_used_public_ips': True, 'cloud_composer_connection_subnetwork': 'cloud_composer_connection_subnetwork_value', 'networking_config': {'connection_type': 1}}, 'web_server_network_access_control': {'allowed_ip_ranges': [{'value': 'value_value', 'description': 'description_value'}]}, 'database_config': {'machine_type': 'machine_type_value', 'zone': 'zone_value'}, 'web_server_config': {'machine_type': 'machine_type_value'}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'maintenance_window': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'recurrence': 'recurrence_value'}, 'workloads_config': {'scheduler': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}, 'web_server': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053}, 'worker': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'min_count': 972, 'max_count': 974}, 'triggerer': {'count': 553, 'cpu': 0.328, 'memory_gb': 0.961}, 'dag_processor': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}}, 'environment_size': 1, 'airflow_uri': 'airflow_uri_value', 'airflow_byoid_uri': 'airflow_byoid_uri_value', 'master_authorized_networks_config': {'enabled': True, 'cidr_blocks': [{'display_name': 'display_name_value', 'cidr_block': 'cidr_block_value'}]}, 'recovery_config': {'scheduled_snapshots_config': {'enabled': True, 'snapshot_location': 'snapshot_location_value', 'snapshot_creation_schedule': 'snapshot_creation_schedule_value', 'time_zone': 'time_zone_value'}}, 'resilience_mode': 1, 'data_retention_config': {'airflow_metadata_retention_config': {'retention_mode': 1, 'retention_days': 1512}, 'task_logs_retention_config': {'storage_mode': 1}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': True, 'satisfies_pzi': True, 'storage_config': {'bucket': 'bucket_value'}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = environments.CreateEnvironmentRequest.meta.fields["environment"] - - 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["environment"].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["environment"][field])): - del request_init["environment"][field][i][subfield] - else: - del request_init["environment"][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_environment(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_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_environment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.CreateEnvironmentRequest.pb(environments.CreateEnvironmentRequest()) - 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 = environments.CreateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.create_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_environment_rest_bad_request(request_type=environments.GetEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) - - -@pytest.mark.parametrize("request_type", [ - environments.GetEnvironmentRequest, - dict, -]) -def test_get_environment_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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 = environments.Environment( - name='name_value', - uuid='uuid_value', - state=environments.Environment.State.CREATING, - satisfies_pzs=True, - satisfies_pzi=True, - ) - - # 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 = environments.Environment.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_environment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.Environment) - assert response.name == 'name_value' - assert response.uuid == 'uuid_value' - assert response.state == environments.Environment.State.CREATING - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_environment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.GetEnvironmentRequest.pb(environments.GetEnvironmentRequest()) - 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 = environments.Environment.to_json(environments.Environment()) - req.return_value.content = return_value - - request = environments.GetEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.Environment() - post_with_metadata.return_value = environments.Environment(), metadata - - client.get_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_environments_rest_bad_request(request_type=environments.ListEnvironmentsRequest): - client = EnvironmentsClient( - 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_environments(request) - - -@pytest.mark.parametrize("request_type", [ - environments.ListEnvironmentsRequest, - dict, -]) -def test_list_environments_rest_call_success(request_type): - client = EnvironmentsClient( - 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 = environments.ListEnvironmentsResponse( - 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 = environments.ListEnvironmentsResponse.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_environments(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_environments_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_environments") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_environments_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_environments") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.ListEnvironmentsRequest.pb(environments.ListEnvironmentsRequest()) - 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 = environments.ListEnvironmentsResponse.to_json(environments.ListEnvironmentsResponse()) - req.return_value.content = return_value - - request = environments.ListEnvironmentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListEnvironmentsResponse() - post_with_metadata.return_value = environments.ListEnvironmentsResponse(), metadata - - client.list_environments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_environment_rest_bad_request(request_type=environments.UpdateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateEnvironmentRequest, - dict, -]) -def test_update_environment_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3'} - request_init["environment"] = {'name': 'name_value', 'config': {'gke_cluster': 'gke_cluster_value', 'dag_gcs_prefix': 'dag_gcs_prefix_value', 'node_count': 1070, 'software_config': {'image_version': 'image_version_value', 'airflow_config_overrides': {}, 'pypi_packages': {}, 'env_variables': {}, 'python_version': 'python_version_value', 'scheduler_count': 1607, 'cloud_data_lineage_integration': {'enabled': True}, 'web_server_plugins_mode': 1}, 'node_config': {'location': 'location_value', 'machine_type': 'machine_type_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'disk_size_gb': 1261, 'oauth_scopes': ['oauth_scopes_value1', 'oauth_scopes_value2'], 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'ip_allocation_policy': {'use_ip_aliases': True, 'cluster_secondary_range_name': 'cluster_secondary_range_name_value', 'cluster_ipv4_cidr_block': 'cluster_ipv4_cidr_block_value', 'services_secondary_range_name': 'services_secondary_range_name_value', 'services_ipv4_cidr_block': 'services_ipv4_cidr_block_value'}, 'enable_ip_masq_agent': True, 'composer_network_attachment': 'composer_network_attachment_value', 'composer_internal_ipv4_cidr_block': 'composer_internal_ipv4_cidr_block_value'}, 'private_environment_config': {'enable_private_environment': True, 'enable_private_builds_only': True, 'private_cluster_config': {'enable_private_endpoint': True, 'master_ipv4_cidr_block': 'master_ipv4_cidr_block_value', 'master_ipv4_reserved_range': 'master_ipv4_reserved_range_value'}, 'web_server_ipv4_cidr_block': 'web_server_ipv4_cidr_block_value', 'cloud_sql_ipv4_cidr_block': 'cloud_sql_ipv4_cidr_block_value', 'web_server_ipv4_reserved_range': 'web_server_ipv4_reserved_range_value', 'cloud_composer_network_ipv4_cidr_block': 'cloud_composer_network_ipv4_cidr_block_value', 'cloud_composer_network_ipv4_reserved_range': 'cloud_composer_network_ipv4_reserved_range_value', 'enable_privately_used_public_ips': True, 'cloud_composer_connection_subnetwork': 'cloud_composer_connection_subnetwork_value', 'networking_config': {'connection_type': 1}}, 'web_server_network_access_control': {'allowed_ip_ranges': [{'value': 'value_value', 'description': 'description_value'}]}, 'database_config': {'machine_type': 'machine_type_value', 'zone': 'zone_value'}, 'web_server_config': {'machine_type': 'machine_type_value'}, 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'maintenance_window': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'recurrence': 'recurrence_value'}, 'workloads_config': {'scheduler': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}, 'web_server': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053}, 'worker': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'min_count': 972, 'max_count': 974}, 'triggerer': {'count': 553, 'cpu': 0.328, 'memory_gb': 0.961}, 'dag_processor': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}}, 'environment_size': 1, 'airflow_uri': 'airflow_uri_value', 'airflow_byoid_uri': 'airflow_byoid_uri_value', 'master_authorized_networks_config': {'enabled': True, 'cidr_blocks': [{'display_name': 'display_name_value', 'cidr_block': 'cidr_block_value'}]}, 'recovery_config': {'scheduled_snapshots_config': {'enabled': True, 'snapshot_location': 'snapshot_location_value', 'snapshot_creation_schedule': 'snapshot_creation_schedule_value', 'time_zone': 'time_zone_value'}}, 'resilience_mode': 1, 'data_retention_config': {'airflow_metadata_retention_config': {'retention_mode': 1, 'retention_days': 1512}, 'task_logs_retention_config': {'storage_mode': 1}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': True, 'satisfies_pzi': True, 'storage_config': {'bucket': 'bucket_value'}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = environments.UpdateEnvironmentRequest.meta.fields["environment"] - - 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["environment"].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["environment"][field])): - del request_init["environment"][field][i][subfield] - else: - del request_init["environment"][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_environment(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_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_environment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.UpdateEnvironmentRequest.pb(environments.UpdateEnvironmentRequest()) - 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 = environments.UpdateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.update_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_environment_rest_bad_request(request_type=environments.DeleteEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteEnvironmentRequest, - dict, -]) -def test_delete_environment_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(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_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_delete_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_delete_environment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_delete_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.DeleteEnvironmentRequest.pb(environments.DeleteEnvironmentRequest()) - 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 = environments.DeleteEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.delete_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_execute_airflow_command_rest_bad_request(request_type=environments.ExecuteAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.execute_airflow_command(request) - - -@pytest.mark.parametrize("request_type", [ - environments.ExecuteAirflowCommandRequest, - dict, -]) -def test_execute_airflow_command_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.ExecuteAirflowCommandResponse( - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - error='error_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 = environments.ExecuteAirflowCommandResponse.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.execute_airflow_command(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.ExecuteAirflowCommandResponse) - assert response.execution_id == 'execution_id_value' - assert response.pod == 'pod_value' - assert response.pod_namespace == 'pod_namespace_value' - assert response.error == 'error_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_execute_airflow_command_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_execute_airflow_command") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_execute_airflow_command_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_execute_airflow_command") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.ExecuteAirflowCommandRequest.pb(environments.ExecuteAirflowCommandRequest()) - 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 = environments.ExecuteAirflowCommandResponse.to_json(environments.ExecuteAirflowCommandResponse()) - req.return_value.content = return_value - - request = environments.ExecuteAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ExecuteAirflowCommandResponse() - post_with_metadata.return_value = environments.ExecuteAirflowCommandResponse(), metadata - - client.execute_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_stop_airflow_command_rest_bad_request(request_type=environments.StopAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.stop_airflow_command(request) - - -@pytest.mark.parametrize("request_type", [ - environments.StopAirflowCommandRequest, - dict, -]) -def test_stop_airflow_command_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.StopAirflowCommandResponse( - is_done=True, - output=['output_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 = environments.StopAirflowCommandResponse.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.stop_airflow_command(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.StopAirflowCommandResponse) - assert response.is_done is True - assert response.output == ['output_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_stop_airflow_command_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_stop_airflow_command") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_stop_airflow_command_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_stop_airflow_command") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.StopAirflowCommandRequest.pb(environments.StopAirflowCommandRequest()) - 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 = environments.StopAirflowCommandResponse.to_json(environments.StopAirflowCommandResponse()) - req.return_value.content = return_value - - request = environments.StopAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.StopAirflowCommandResponse() - post_with_metadata.return_value = environments.StopAirflowCommandResponse(), metadata - - client.stop_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_poll_airflow_command_rest_bad_request(request_type=environments.PollAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.poll_airflow_command(request) - - -@pytest.mark.parametrize("request_type", [ - environments.PollAirflowCommandRequest, - dict, -]) -def test_poll_airflow_command_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.PollAirflowCommandResponse( - output_end=True, - ) - - # 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 = environments.PollAirflowCommandResponse.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.poll_airflow_command(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.PollAirflowCommandResponse) - assert response.output_end is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_poll_airflow_command_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_poll_airflow_command") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_poll_airflow_command_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_poll_airflow_command") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.PollAirflowCommandRequest.pb(environments.PollAirflowCommandRequest()) - 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 = environments.PollAirflowCommandResponse.to_json(environments.PollAirflowCommandResponse()) - req.return_value.content = return_value - - request = environments.PollAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.PollAirflowCommandResponse() - post_with_metadata.return_value = environments.PollAirflowCommandResponse(), metadata - - client.poll_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_workloads_rest_bad_request(request_type=environments.ListWorkloadsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_workloads(request) - - -@pytest.mark.parametrize("request_type", [ - environments.ListWorkloadsRequest, - dict, -]) -def test_list_workloads_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListWorkloadsResponse( - 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 = environments.ListWorkloadsResponse.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_workloads(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkloadsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workloads_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_workloads") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_workloads_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_workloads") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.ListWorkloadsRequest.pb(environments.ListWorkloadsRequest()) - 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 = environments.ListWorkloadsResponse.to_json(environments.ListWorkloadsResponse()) - req.return_value.content = return_value - - request = environments.ListWorkloadsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListWorkloadsResponse() - post_with_metadata.return_value = environments.ListWorkloadsResponse(), metadata - - client.list_workloads(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_check_upgrade_rest_bad_request(request_type=environments.CheckUpgradeRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.check_upgrade(request) - - -@pytest.mark.parametrize("request_type", [ - environments.CheckUpgradeRequest, - dict, -]) -def test_check_upgrade_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.check_upgrade(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_check_upgrade_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_check_upgrade") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_check_upgrade_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_check_upgrade") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.CheckUpgradeRequest.pb(environments.CheckUpgradeRequest()) - 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 = environments.CheckUpgradeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.check_upgrade(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_user_workloads_secret_rest_bad_request(request_type=environments.CreateUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_secret(request) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsSecretRequest, - dict, -]) -def test_create_user_workloads_secret_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} - request_init["user_workloads_secret"] = {'name': 'name_value', 'data': {}} - # 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 = environments.CreateUserWorkloadsSecretRequest.meta.fields["user_workloads_secret"] - - 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["user_workloads_secret"].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["user_workloads_secret"][field])): - del request_init["user_workloads_secret"][field][i][subfield] - else: - del request_init["user_workloads_secret"][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 = environments.UserWorkloadsSecret( - 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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_user_workloads_secret_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_user_workloads_secret") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_user_workloads_secret_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_user_workloads_secret") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.CreateUserWorkloadsSecretRequest.pb(environments.CreateUserWorkloadsSecretRequest()) - 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - req.return_value.content = return_value - - request = environments.CreateUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata - - client.create_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_user_workloads_secret_rest_bad_request(request_type=environments.GetUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsSecretRequest, - dict, -]) -def test_get_user_workloads_secret_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = environments.UserWorkloadsSecret( - 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 = environments.UserWorkloadsSecret.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_user_workloads_secret(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_user_workloads_secret_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_user_workloads_secret") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_user_workloads_secret_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_user_workloads_secret") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.GetUserWorkloadsSecretRequest.pb(environments.GetUserWorkloadsSecretRequest()) - 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - req.return_value.content = return_value - - request = environments.GetUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata - - client.get_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_user_workloads_secrets_rest_bad_request(request_type=environments.ListUserWorkloadsSecretsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_secrets(request) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsSecretsRequest, - dict, -]) -def test_list_user_workloads_secrets_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsSecretsResponse( - 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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsSecretsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_user_workloads_secrets_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_user_workloads_secrets") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_user_workloads_secrets_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_user_workloads_secrets") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.ListUserWorkloadsSecretsRequest.pb(environments.ListUserWorkloadsSecretsRequest()) - 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 = environments.ListUserWorkloadsSecretsResponse.to_json(environments.ListUserWorkloadsSecretsResponse()) - req.return_value.content = return_value - - request = environments.ListUserWorkloadsSecretsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListUserWorkloadsSecretsResponse() - post_with_metadata.return_value = environments.ListUserWorkloadsSecretsResponse(), metadata - - client.list_user_workloads_secrets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_user_workloads_secret_rest_bad_request(request_type=environments.UpdateUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateUserWorkloadsSecretRequest, - dict, -]) -def test_update_user_workloads_secret_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4'}} - request_init["user_workloads_secret"] = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4', 'data': {}} - # 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 = environments.UpdateUserWorkloadsSecretRequest.meta.fields["user_workloads_secret"] - - 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["user_workloads_secret"].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["user_workloads_secret"][field])): - del request_init["user_workloads_secret"][field][i][subfield] - else: - del request_init["user_workloads_secret"][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 = environments.UserWorkloadsSecret( - 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 = environments.UserWorkloadsSecret.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.update_user_workloads_secret(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_user_workloads_secret_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_user_workloads_secret") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_user_workloads_secret_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_user_workloads_secret") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.UpdateUserWorkloadsSecretRequest.pb(environments.UpdateUserWorkloadsSecretRequest()) - 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - req.return_value.content = return_value - - request = environments.UpdateUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata - - client.update_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_user_workloads_secret_rest_bad_request(request_type=environments.DeleteUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsSecretRequest, - dict, -]) -def test_delete_user_workloads_secret_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = 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_user_workloads_secret(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_user_workloads_secret_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "pre_delete_user_workloads_secret") as pre: - pre.assert_not_called() - pb_message = environments.DeleteUserWorkloadsSecretRequest.pb(environments.DeleteUserWorkloadsSecretRequest()) - 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"} - - request = environments.DeleteUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_create_user_workloads_config_map_rest_bad_request(request_type=environments.CreateUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_config_map(request) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsConfigMapRequest, - dict, -]) -def test_create_user_workloads_config_map_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} - request_init["user_workloads_config_map"] = {'name': 'name_value', 'data': {}} - # 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 = environments.CreateUserWorkloadsConfigMapRequest.meta.fields["user_workloads_config_map"] - - 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["user_workloads_config_map"].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["user_workloads_config_map"][field])): - del request_init["user_workloads_config_map"][field][i][subfield] - else: - del request_init["user_workloads_config_map"][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 = environments.UserWorkloadsConfigMap( - 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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_user_workloads_config_map_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_user_workloads_config_map") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_user_workloads_config_map_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_user_workloads_config_map") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.CreateUserWorkloadsConfigMapRequest.pb(environments.CreateUserWorkloadsConfigMapRequest()) - 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - req.return_value.content = return_value - - request = environments.CreateUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata - - client.create_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_user_workloads_config_map_rest_bad_request(request_type=environments.GetUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsConfigMapRequest, - dict, -]) -def test_get_user_workloads_config_map_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = environments.UserWorkloadsConfigMap( - 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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_user_workloads_config_map_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_user_workloads_config_map") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_user_workloads_config_map_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_user_workloads_config_map") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.GetUserWorkloadsConfigMapRequest.pb(environments.GetUserWorkloadsConfigMapRequest()) - 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - req.return_value.content = return_value - - request = environments.GetUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata - - client.get_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_user_workloads_config_maps_rest_bad_request(request_type=environments.ListUserWorkloadsConfigMapsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_config_maps(request) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsConfigMapsRequest, - dict, -]) -def test_list_user_workloads_config_maps_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsConfigMapsResponse( - 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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsConfigMapsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_user_workloads_config_maps_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_user_workloads_config_maps") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_user_workloads_config_maps_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_user_workloads_config_maps") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.ListUserWorkloadsConfigMapsRequest.pb(environments.ListUserWorkloadsConfigMapsRequest()) - 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 = environments.ListUserWorkloadsConfigMapsResponse.to_json(environments.ListUserWorkloadsConfigMapsResponse()) - req.return_value.content = return_value - - request = environments.ListUserWorkloadsConfigMapsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListUserWorkloadsConfigMapsResponse() - post_with_metadata.return_value = environments.ListUserWorkloadsConfigMapsResponse(), metadata - - client.list_user_workloads_config_maps(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_user_workloads_config_map_rest_bad_request(request_type=environments.UpdateUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateUserWorkloadsConfigMapRequest, - dict, -]) -def test_update_user_workloads_config_map_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4'}} - request_init["user_workloads_config_map"] = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4', 'data': {}} - # 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 = environments.UpdateUserWorkloadsConfigMapRequest.meta.fields["user_workloads_config_map"] - - 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["user_workloads_config_map"].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["user_workloads_config_map"][field])): - del request_init["user_workloads_config_map"][field][i][subfield] - else: - del request_init["user_workloads_config_map"][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 = environments.UserWorkloadsConfigMap( - 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 = environments.UserWorkloadsConfigMap.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.update_user_workloads_config_map(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_user_workloads_config_map_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_user_workloads_config_map") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_user_workloads_config_map_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_user_workloads_config_map") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.UpdateUserWorkloadsConfigMapRequest.pb(environments.UpdateUserWorkloadsConfigMapRequest()) - 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - req.return_value.content = return_value - - request = environments.UpdateUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata - - client.update_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_user_workloads_config_map_rest_bad_request(request_type=environments.DeleteUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsConfigMapRequest, - dict, -]) -def test_delete_user_workloads_config_map_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = 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_user_workloads_config_map(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_user_workloads_config_map_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "pre_delete_user_workloads_config_map") as pre: - pre.assert_not_called() - pb_message = environments.DeleteUserWorkloadsConfigMapRequest.pb(environments.DeleteUserWorkloadsConfigMapRequest()) - 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"} - - request = environments.DeleteUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_save_snapshot_rest_bad_request(request_type=environments.SaveSnapshotRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.save_snapshot(request) - - -@pytest.mark.parametrize("request_type", [ - environments.SaveSnapshotRequest, - dict, -]) -def test_save_snapshot_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.save_snapshot(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_save_snapshot_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_save_snapshot") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_save_snapshot_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_save_snapshot") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.SaveSnapshotRequest.pb(environments.SaveSnapshotRequest()) - 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 = environments.SaveSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.save_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_load_snapshot_rest_bad_request(request_type=environments.LoadSnapshotRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.load_snapshot(request) - - -@pytest.mark.parametrize("request_type", [ - environments.LoadSnapshotRequest, - dict, -]) -def test_load_snapshot_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.load_snapshot(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_load_snapshot_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_load_snapshot") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_load_snapshot_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_load_snapshot") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.LoadSnapshotRequest.pb(environments.LoadSnapshotRequest()) - 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 = environments.LoadSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.load_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_database_failover_rest_bad_request(request_type=environments.DatabaseFailoverRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.database_failover(request) - - -@pytest.mark.parametrize("request_type", [ - environments.DatabaseFailoverRequest, - dict, -]) -def test_database_failover_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.database_failover(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_database_failover_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_database_failover") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_database_failover_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_database_failover") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.DatabaseFailoverRequest.pb(environments.DatabaseFailoverRequest()) - 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 = environments.DatabaseFailoverRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.database_failover(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_fetch_database_properties_rest_bad_request(request_type=environments.FetchDatabasePropertiesRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.fetch_database_properties(request) - - -@pytest.mark.parametrize("request_type", [ - environments.FetchDatabasePropertiesRequest, - dict, -]) -def test_fetch_database_properties_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.FetchDatabasePropertiesResponse( - primary_gce_zone='primary_gce_zone_value', - secondary_gce_zone='secondary_gce_zone_value', - is_failover_replica_available=True, - ) - - # 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 = environments.FetchDatabasePropertiesResponse.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.fetch_database_properties(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.FetchDatabasePropertiesResponse) - assert response.primary_gce_zone == 'primary_gce_zone_value' - assert response.secondary_gce_zone == 'secondary_gce_zone_value' - assert response.is_failover_replica_available is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_database_properties_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_fetch_database_properties") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_fetch_database_properties_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_fetch_database_properties") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.FetchDatabasePropertiesRequest.pb(environments.FetchDatabasePropertiesRequest()) - 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 = environments.FetchDatabasePropertiesResponse.to_json(environments.FetchDatabasePropertiesResponse()) - req.return_value.content = return_value - - request = environments.FetchDatabasePropertiesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.FetchDatabasePropertiesResponse() - post_with_metadata.return_value = environments.FetchDatabasePropertiesResponse(), metadata - - client.fetch_database_properties(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = EnvironmentsClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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_environment_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - client.create_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateEnvironmentRequest() - - 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_environment_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - client.get_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetEnvironmentRequest() - - 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_environments_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - client.list_environments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListEnvironmentsRequest() - - 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_environment_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - client.update_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateEnvironmentRequest() - - 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_environment_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - client.delete_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteEnvironmentRequest() - - 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_execute_airflow_command_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - client.execute_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ExecuteAirflowCommandRequest() - - 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_stop_airflow_command_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - client.stop_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.StopAirflowCommandRequest() - - 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_poll_airflow_command_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - client.poll_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.PollAirflowCommandRequest() - - 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_workloads_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - client.list_workloads(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListWorkloadsRequest() - - 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_check_upgrade_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - client.check_upgrade(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CheckUpgradeRequest() - - 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_user_workloads_secret_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - client.create_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - client.get_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsSecretRequest() - - 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_user_workloads_secrets_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - client.list_user_workloads_secrets(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsSecretsRequest() - - 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_user_workloads_secret_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - client.update_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - client.delete_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsSecretRequest() - - 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_user_workloads_config_map_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - client.create_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - client.get_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_maps_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - client.list_user_workloads_config_maps(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsConfigMapsRequest() - - 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_user_workloads_config_map_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - client.update_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - client.delete_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsConfigMapRequest() - - 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_save_snapshot_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - client.save_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.SaveSnapshotRequest() - - 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_load_snapshot_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - client.load_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.LoadSnapshotRequest() - - 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_database_failover_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - client.database_failover(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DatabaseFailoverRequest() - - 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_fetch_database_properties_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - client.fetch_database_properties(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.FetchDatabasePropertiesRequest() - - assert args[0] == request_msg - - -def test_environments_rest_lro_client(): - client = EnvironmentsClient( - 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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.EnvironmentsGrpcTransport, - ) - -def test_environments_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EnvironmentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_environments_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.orchestration.airflow.service_v1.services.environments.transports.EnvironmentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EnvironmentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_environment', - 'get_environment', - 'list_environments', - 'update_environment', - 'delete_environment', - 'execute_airflow_command', - 'stop_airflow_command', - 'poll_airflow_command', - 'list_workloads', - 'check_upgrade', - 'create_user_workloads_secret', - 'get_user_workloads_secret', - 'list_user_workloads_secrets', - 'update_user_workloads_secret', - 'delete_user_workloads_secret', - 'create_user_workloads_config_map', - 'get_user_workloads_config_map', - 'list_user_workloads_config_maps', - 'update_user_workloads_config_map', - 'delete_user_workloads_config_map', - 'save_snapshot', - 'load_snapshot', - 'database_failover', - 'fetch_database_properties', - 'get_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_environments_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.orchestration.airflow.service_v1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - 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_environments_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.orchestration.airflow.service_v1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport() - adc.assert_called_once() - - -def test_environments_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) - EnvironmentsClient() - 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.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -def test_environments_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.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - transports.EnvironmentsRestTransport, - ], -) -def test_environments_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.EnvironmentsGrpcTransport, grpc_helpers), - (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_environments_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( - "composer.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="composer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_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_environments_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.EnvironmentsRestTransport ( - 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_environments_host_no_port(transport_name): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://composer.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_environments_host_with_port(transport_name): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'composer.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://composer.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_environments_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EnvironmentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EnvironmentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_environment._session - session2 = client2.transport.create_environment._session - assert session1 != session2 - session1 = client1.transport.get_environment._session - session2 = client2.transport.get_environment._session - assert session1 != session2 - session1 = client1.transport.list_environments._session - session2 = client2.transport.list_environments._session - assert session1 != session2 - session1 = client1.transport.update_environment._session - session2 = client2.transport.update_environment._session - assert session1 != session2 - session1 = client1.transport.delete_environment._session - session2 = client2.transport.delete_environment._session - assert session1 != session2 - session1 = client1.transport.execute_airflow_command._session - session2 = client2.transport.execute_airflow_command._session - assert session1 != session2 - session1 = client1.transport.stop_airflow_command._session - session2 = client2.transport.stop_airflow_command._session - assert session1 != session2 - session1 = client1.transport.poll_airflow_command._session - session2 = client2.transport.poll_airflow_command._session - assert session1 != session2 - session1 = client1.transport.list_workloads._session - session2 = client2.transport.list_workloads._session - assert session1 != session2 - session1 = client1.transport.check_upgrade._session - session2 = client2.transport.check_upgrade._session - assert session1 != session2 - session1 = client1.transport.create_user_workloads_secret._session - session2 = client2.transport.create_user_workloads_secret._session - assert session1 != session2 - session1 = client1.transport.get_user_workloads_secret._session - session2 = client2.transport.get_user_workloads_secret._session - assert session1 != session2 - session1 = client1.transport.list_user_workloads_secrets._session - session2 = client2.transport.list_user_workloads_secrets._session - assert session1 != session2 - session1 = client1.transport.update_user_workloads_secret._session - session2 = client2.transport.update_user_workloads_secret._session - assert session1 != session2 - session1 = client1.transport.delete_user_workloads_secret._session - session2 = client2.transport.delete_user_workloads_secret._session - assert session1 != session2 - session1 = client1.transport.create_user_workloads_config_map._session - session2 = client2.transport.create_user_workloads_config_map._session - assert session1 != session2 - session1 = client1.transport.get_user_workloads_config_map._session - session2 = client2.transport.get_user_workloads_config_map._session - assert session1 != session2 - session1 = client1.transport.list_user_workloads_config_maps._session - session2 = client2.transport.list_user_workloads_config_maps._session - assert session1 != session2 - session1 = client1.transport.update_user_workloads_config_map._session - session2 = client2.transport.update_user_workloads_config_map._session - assert session1 != session2 - session1 = client1.transport.delete_user_workloads_config_map._session - session2 = client2.transport.delete_user_workloads_config_map._session - assert session1 != session2 - session1 = client1.transport.save_snapshot._session - session2 = client2.transport.save_snapshot._session - assert session1 != session2 - session1 = client1.transport.load_snapshot._session - session2 = client2.transport.load_snapshot._session - assert session1 != session2 - session1 = client1.transport.database_failover._session - session2 = client2.transport.database_failover._session - assert session1 != session2 - session1 = client1.transport.fetch_database_properties._session - session2 = client2.transport.fetch_database_properties._session - assert session1 != session2 -def test_environments_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EnvironmentsGrpcTransport( - 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_environments_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EnvironmentsGrpcAsyncIOTransport( - 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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_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_environments_grpc_lro_client(): - client = EnvironmentsClient( - 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_environments_grpc_lro_async_client(): - client = EnvironmentsAsyncClient( - 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_environment_path(): - project = "squid" - location = "clam" - environment = "whelk" - expected = "projects/{project}/locations/{location}/environments/{environment}".format(project=project, location=location, environment=environment, ) - actual = EnvironmentsClient.environment_path(project, location, environment) - assert expected == actual - - -def test_parse_environment_path(): - expected = { - "project": "octopus", - "location": "oyster", - "environment": "nudibranch", - } - path = EnvironmentsClient.environment_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_environment_path(path) - assert expected == actual - -def test_user_workloads_config_map_path(): - project = "cuttlefish" - location = "mussel" - environment = "winkle" - user_workloads_config_map = "nautilus" - expected = "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsConfigMaps/{user_workloads_config_map}".format(project=project, location=location, environment=environment, user_workloads_config_map=user_workloads_config_map, ) - actual = EnvironmentsClient.user_workloads_config_map_path(project, location, environment, user_workloads_config_map) - assert expected == actual - - -def test_parse_user_workloads_config_map_path(): - expected = { - "project": "scallop", - "location": "abalone", - "environment": "squid", - "user_workloads_config_map": "clam", - } - path = EnvironmentsClient.user_workloads_config_map_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_user_workloads_config_map_path(path) - assert expected == actual - -def test_user_workloads_secret_path(): - project = "whelk" - location = "octopus" - environment = "oyster" - user_workloads_secret = "nudibranch" - expected = "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsSecrets/{user_workloads_secret}".format(project=project, location=location, environment=environment, user_workloads_secret=user_workloads_secret, ) - actual = EnvironmentsClient.user_workloads_secret_path(project, location, environment, user_workloads_secret) - assert expected == actual - - -def test_parse_user_workloads_secret_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "environment": "winkle", - "user_workloads_secret": "nautilus", - } - path = EnvironmentsClient.user_workloads_secret_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_user_workloads_secret_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EnvironmentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = EnvironmentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = EnvironmentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = EnvironmentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = EnvironmentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.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 = EnvironmentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = EnvironmentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.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.EnvironmentsTransport, '_prep_wrapped_messages') as prep: - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EnvironmentsTransport, '_prep_wrapped_messages') as prep: - transport_class = EnvironmentsClient.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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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_get_operation(transport: str = "grpc"): - client = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport), -]) -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-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py deleted file mode 100644 index e9bfcea08472..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py +++ /dev/null @@ -1,2847 +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 gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -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.orchestration.airflow.service_v1.services.image_versions import ImageVersionsAsyncClient -from google.cloud.orchestration.airflow.service_v1.services.image_versions import ImageVersionsClient -from google.cloud.orchestration.airflow.service_v1.services.image_versions import pagers -from google.cloud.orchestration.airflow.service_v1.services.image_versions import transports -from google.cloud.orchestration.airflow.service_v1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -import google.auth - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) - - -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 ImageVersionsClient._get_default_mtls_endpoint(None) is None - assert ImageVersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ImageVersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ImageVersionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ImageVersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ImageVersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ImageVersionsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ImageVersionsClient._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 ImageVersionsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ImageVersionsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ImageVersionsClient._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 ImageVersionsClient._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 ImageVersionsClient._get_client_cert_source(None, False) is None - assert ImageVersionsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ImageVersionsClient._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 ImageVersionsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ImageVersionsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ImageVersionsClient._DEFAULT_UNIVERSE - default_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ImageVersionsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ImageVersionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "always") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - assert ImageVersionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - assert ImageVersionsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ImageVersionsClient._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 ImageVersionsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ImageVersionsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ImageVersionsClient._get_universe_domain(None, None) == ImageVersionsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ImageVersionsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) -def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): - cred = mock.Mock(["get_cred_info"]) - cred.get_cred_info = mock.Mock(return_value=cred_info_json) - client = ImageVersionsClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401,403,404,500]) -def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): - cred = mock.Mock([]) - assert not hasattr(cred, "get_cred_info") - client = ImageVersionsClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -@pytest.mark.parametrize("client_class,transport_name", [ - (ImageVersionsClient, "grpc"), - (ImageVersionsAsyncClient, "grpc_asyncio"), - (ImageVersionsClient, "rest"), -]) -def test_image_versions_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 == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://composer.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ImageVersionsGrpcTransport, "grpc"), - (transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ImageVersionsRestTransport, "rest"), -]) -def test_image_versions_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", [ - (ImageVersionsClient, "grpc"), - (ImageVersionsAsyncClient, "grpc_asyncio"), - (ImageVersionsClient, "rest"), -]) -def test_image_versions_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 == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://composer.googleapis.com' - ) - - -def test_image_versions_client_get_transport_class(): - transport = ImageVersionsClient.get_transport_class() - available_transports = [ - transports.ImageVersionsGrpcTransport, - transports.ImageVersionsRestTransport, - ] - assert transport in available_transports - - transport = ImageVersionsClient.get_transport_class("grpc") - assert transport == transports.ImageVersionsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), -]) -@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) -def test_image_versions_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(ImageVersionsClient, '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(ImageVersionsClient, '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", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", "true"), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", "false"), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", "true"), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", "false"), -]) -@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_image_versions_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", [ - ImageVersionsClient, ImageVersionsAsyncClient -]) -@mock.patch.object(ImageVersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageVersionsAsyncClient)) -def test_image_versions_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", [ - ImageVersionsClient, ImageVersionsAsyncClient -]) -@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) -def test_image_versions_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ImageVersionsClient._DEFAULT_UNIVERSE - default_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ImageVersionsClient._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", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), -]) -def test_image_versions_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", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", grpc_helpers), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", None), -]) -def test_image_versions_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_image_versions_client_client_options_from_dict(): - with mock.patch('google.cloud.orchestration.airflow.service_v1.services.image_versions.transports.ImageVersionsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ImageVersionsClient( - 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", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", grpc_helpers), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_image_versions_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( - "composer.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="composer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - image_versions.ListImageVersionsRequest, - dict, -]) -def test_list_image_versions(request_type, transport: str = 'grpc'): - client = ImageVersionsClient( - 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_image_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = image_versions.ListImageVersionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = image_versions.ListImageVersionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImageVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_image_versions_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 = ImageVersionsClient( - 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 = image_versions.ListImageVersionsRequest( - 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_image_versions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_image_versions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == image_versions.ListImageVersionsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_image_versions_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 = ImageVersionsClient( - 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_image_versions 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_image_versions] = mock_rpc - request = {} - client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_image_versions(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_image_versions_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 = ImageVersionsAsyncClient( - 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_image_versions 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_image_versions] = mock_rpc - - request = {} - await client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_image_versions(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_image_versions_async(transport: str = 'grpc_asyncio', request_type=image_versions.ListImageVersionsRequest): - client = ImageVersionsAsyncClient( - 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_image_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = image_versions.ListImageVersionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImageVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_image_versions_async_from_dict(): - await test_list_image_versions_async(request_type=dict) - -def test_list_image_versions_field_headers(): - client = ImageVersionsClient( - 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 = image_versions.ListImageVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - call.return_value = image_versions.ListImageVersionsResponse() - client.list_image_versions(request) - - # Establish that the 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_image_versions_field_headers_async(): - client = ImageVersionsAsyncClient( - 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 = image_versions.ListImageVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse()) - await client.list_image_versions(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_image_versions_flattened(): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = image_versions.ListImageVersionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_image_versions( - 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_image_versions_flattened_error(): - client = ImageVersionsClient( - 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_image_versions( - image_versions.ListImageVersionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_image_versions_flattened_async(): - client = ImageVersionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = image_versions.ListImageVersionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_image_versions( - 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_image_versions_flattened_error_async(): - client = ImageVersionsAsyncClient( - 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_image_versions( - image_versions.ListImageVersionsRequest(), - parent='parent_value', - ) - - -def test_list_image_versions_pager(transport_name: str = "grpc"): - client = ImageVersionsClient( - 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_image_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - next_page_token='abc', - ), - image_versions.ListImageVersionsResponse( - image_versions=[], - next_page_token='def', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - ], - next_page_token='ghi', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_image_versions(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, image_versions.ImageVersion) - for i in results) -def test_list_image_versions_pages(transport_name: str = "grpc"): - client = ImageVersionsClient( - 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_image_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - next_page_token='abc', - ), - image_versions.ListImageVersionsResponse( - image_versions=[], - next_page_token='def', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - ], - next_page_token='ghi', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_image_versions(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_image_versions_async_pager(): - client = ImageVersionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - next_page_token='abc', - ), - image_versions.ListImageVersionsResponse( - image_versions=[], - next_page_token='def', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - ], - next_page_token='ghi', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_image_versions(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, image_versions.ImageVersion) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_image_versions_async_pages(): - client = ImageVersionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - next_page_token='abc', - ), - image_versions.ListImageVersionsResponse( - image_versions=[], - next_page_token='def', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - ], - next_page_token='ghi', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - ), - 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_image_versions(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_image_versions_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 = ImageVersionsClient( - 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_image_versions 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_image_versions] = mock_rpc - - request = {} - client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_image_versions(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_image_versions_rest_flattened(): - client = ImageVersionsClient( - 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 = image_versions.ListImageVersionsResponse() - - # 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 = image_versions.ListImageVersionsResponse.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_image_versions(**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/*}/imageVersions" % client.transport._host, args[1]) - - -def test_list_image_versions_rest_flattened_error(transport: str = 'rest'): - client = ImageVersionsClient( - 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_image_versions( - image_versions.ListImageVersionsRequest(), - parent='parent_value', - ) - - -def test_list_image_versions_rest_pager(transport: str = 'rest'): - client = ImageVersionsClient( - 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 = ( - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - next_page_token='abc', - ), - image_versions.ListImageVersionsResponse( - image_versions=[], - next_page_token='def', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - ], - next_page_token='ghi', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(image_versions.ListImageVersionsResponse.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_image_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, image_versions.ImageVersion) - for i in results) - - pages = list(client.list_image_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ImageVersionsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ImageVersionsClient( - 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 = ImageVersionsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ImageVersionsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ImageVersionsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ImageVersionsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ImageVersionsGrpcTransport, - transports.ImageVersionsGrpcAsyncIOTransport, - transports.ImageVersionsRestTransport, -]) -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 = ImageVersionsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ImageVersionsClient( - 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_list_image_versions_empty_call_grpc(): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - call.return_value = image_versions.ListImageVersionsResponse() - client.list_image_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = image_versions.ListImageVersionsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ImageVersionsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ImageVersionsAsyncClient( - 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_list_image_versions_empty_call_grpc_asyncio(): - client = ImageVersionsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse( - next_page_token='next_page_token_value', - )) - await client.list_image_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = image_versions.ListImageVersionsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ImageVersionsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_image_versions_rest_bad_request(request_type=image_versions.ListImageVersionsRequest): - client = ImageVersionsClient( - 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_image_versions(request) - - -@pytest.mark.parametrize("request_type", [ - image_versions.ListImageVersionsRequest, - dict, -]) -def test_list_image_versions_rest_call_success(request_type): - client = ImageVersionsClient( - 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 = image_versions.ListImageVersionsResponse( - 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 = image_versions.ListImageVersionsResponse.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_image_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImageVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_image_versions_rest_interceptors(null_interceptor): - transport = transports.ImageVersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ImageVersionsRestInterceptor(), - ) - client = ImageVersionsClient(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.ImageVersionsRestInterceptor, "post_list_image_versions") as post, \ - mock.patch.object(transports.ImageVersionsRestInterceptor, "post_list_image_versions_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ImageVersionsRestInterceptor, "pre_list_image_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = image_versions.ListImageVersionsRequest.pb(image_versions.ListImageVersionsRequest()) - 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 = image_versions.ListImageVersionsResponse.to_json(image_versions.ListImageVersionsResponse()) - req.return_value.content = return_value - - request = image_versions.ListImageVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = image_versions.ListImageVersionsResponse() - post_with_metadata.return_value = image_versions.ListImageVersionsResponse(), metadata - - client.list_image_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = ImageVersionsClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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_list_image_versions_empty_call_rest(): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - client.list_image_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = image_versions.ListImageVersionsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ImageVersionsGrpcTransport, - ) - -def test_image_versions_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ImageVersionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_image_versions_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.orchestration.airflow.service_v1.services.image_versions.transports.ImageVersionsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ImageVersionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_image_versions', - 'get_operation', - 'delete_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_image_versions_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.orchestration.airflow.service_v1.services.image_versions.transports.ImageVersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ImageVersionsTransport( - 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_image_versions_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.orchestration.airflow.service_v1.services.image_versions.transports.ImageVersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ImageVersionsTransport() - adc.assert_called_once() - - -def test_image_versions_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) - ImageVersionsClient() - 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.ImageVersionsGrpcTransport, - transports.ImageVersionsGrpcAsyncIOTransport, - ], -) -def test_image_versions_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.ImageVersionsGrpcTransport, - transports.ImageVersionsGrpcAsyncIOTransport, - transports.ImageVersionsRestTransport, - ], -) -def test_image_versions_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.ImageVersionsGrpcTransport, grpc_helpers), - (transports.ImageVersionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_image_versions_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( - "composer.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="composer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) -def test_image_versions_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_image_versions_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.ImageVersionsRestTransport ( - 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_image_versions_host_no_port(transport_name): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://composer.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_image_versions_host_with_port(transport_name): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'composer.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://composer.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_image_versions_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ImageVersionsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ImageVersionsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_image_versions._session - session2 = client2.transport.list_image_versions._session - assert session1 != session2 -def test_image_versions_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ImageVersionsGrpcTransport( - 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_image_versions_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ImageVersionsGrpcAsyncIOTransport( - 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.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) -def test_image_versions_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.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) -def test_image_versions_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_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ImageVersionsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = ImageVersionsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ImageVersionsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = ImageVersionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = ImageVersionsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ImageVersionsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ImageVersionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = ImageVersionsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ImageVersionsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = ImageVersionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = ImageVersionsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ImageVersionsClient.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 = ImageVersionsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = ImageVersionsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ImageVersionsClient.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.ImageVersionsTransport, '_prep_wrapped_messages') as prep: - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ImageVersionsTransport, '_prep_wrapped_messages') as prep: - transport_class = ImageVersionsClient.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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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_get_operation(transport: str = "grpc"): - client = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport), -]) -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-orchestration-airflow/v1beta1/.coveragerc b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.coveragerc deleted file mode 100644 index 7b27e381927a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/orchestration/airflow/service/__init__.py - google/cloud/orchestration/airflow/service/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-orchestration-airflow/v1beta1/.flake8 b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/.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-orchestration-airflow/v1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/MANIFEST.in deleted file mode 100644 index 20f737545f5e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/orchestration/airflow/service *.py -recursive-include google/cloud/orchestration/airflow/service_v1beta1 *.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/README.rst deleted file mode 100644 index 4f24fd5ece7c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Cloud Orchestration Airflow Service 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 Orchestration Airflow Service 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 - - -Logging -------- - -This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. -Note the following: - -#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. -#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. -#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. - - -Simple, environment-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google -logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged -messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging -event. - -A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. - -- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. -- Invalid logging scopes: :code:`foo`, :code:`123`, etc. - -**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. - - -Examples -^^^^^^^^ - -- Enabling the default handler for all Google-based loggers - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google - -- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 - - -Advanced, code-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can also configure a valid logging scope using Python's standard `logging` mechanism. - - -Examples -^^^^^^^^ - -- Configuring a handler for all Google-based loggers - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - -- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google.cloud.library_v1") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - - -Logging details -~~~~~~~~~~~~~~~ - -#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root - logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set - :code:`logging.getLogger("google").propagate = True` in your code. -#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for - one library, but decide you need to also set up environment-based logging configuration for another library. - - #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual - if the code -based configuration gets applied first. - -#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get - executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. - (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/airflow-service-v1beta1-py.tar.gz b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/airflow-service-v1beta1-py.tar.gz deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/docs/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py deleted file mode 100644 index b97cc0c9fd88..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow-service 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-orchestration-airflow-service" -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 Orchestration Airflow 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-orchestration-airflow-service-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-orchestration-airflow-service.tex", - u"google-cloud-orchestration-airflow-service 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-orchestration-airflow-service", - u"Google Cloud Orchestration Airflow Service 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-orchestration-airflow-service", - u"google-cloud-orchestration-airflow-service Documentation", - author, - "google-cloud-orchestration-airflow-service", - "GAPIC library for Google Cloud Orchestration Airflow Service 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-orchestration-airflow/v1beta1/docs/index.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/index.rst deleted file mode 100644 index 99ae5d015386..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - service_v1beta1/services_ - service_v1beta1/types_ diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/environments.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/environments.rst deleted file mode 100644 index 9a3d3abd2249..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/environments.rst +++ /dev/null @@ -1,10 +0,0 @@ -Environments ------------------------------- - -.. automodule:: google.cloud.orchestration.airflow.service_v1beta1.services.environments - :members: - :inherited-members: - -.. automodule:: google.cloud.orchestration.airflow.service_v1beta1.services.environments.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/image_versions.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/image_versions.rst deleted file mode 100644 index b6b092000589..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/image_versions.rst +++ /dev/null @@ -1,10 +0,0 @@ -ImageVersions -------------------------------- - -.. automodule:: google.cloud.orchestration.airflow.service_v1beta1.services.image_versions - :members: - :inherited-members: - -.. automodule:: google.cloud.orchestration.airflow.service_v1beta1.services.image_versions.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/services_.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/services_.rst deleted file mode 100644 index 028dbc969e68..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/services_.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Orchestration Airflow Service v1beta1 API -=================================================================== -.. toctree:: - :maxdepth: 2 - - environments - image_versions diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/types_.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/types_.rst deleted file mode 100644 index 9caa2086107d..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/service_v1beta1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Orchestration Airflow Service v1beta1 API -================================================================ - -.. automodule:: google.cloud.orchestration.airflow.service_v1beta1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py deleted file mode 100644 index 663bb823e81a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py +++ /dev/null @@ -1,161 +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.orchestration.airflow.service import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.orchestration.airflow.service_v1beta1.services.environments.client import EnvironmentsClient -from google.cloud.orchestration.airflow.service_v1beta1.services.environments.async_client import EnvironmentsAsyncClient -from google.cloud.orchestration.airflow.service_v1beta1.services.image_versions.client import ImageVersionsClient -from google.cloud.orchestration.airflow.service_v1beta1.services.image_versions.async_client import ImageVersionsAsyncClient - -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import AirflowMetadataRetentionPolicyConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CheckUpgradeRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CheckUpgradeResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CloudDataLineageIntegration -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CreateEnvironmentRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CreateUserWorkloadsConfigMapRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import CreateUserWorkloadsSecretRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DatabaseConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DatabaseFailoverRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DatabaseFailoverResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DataRetentionConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DeleteEnvironmentRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DeleteUserWorkloadsConfigMapRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DeleteUserWorkloadsSecretRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import EncryptionConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import Environment -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import EnvironmentConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ExecuteAirflowCommandRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ExecuteAirflowCommandResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import FetchDatabasePropertiesRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import FetchDatabasePropertiesResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import GetEnvironmentRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import GetUserWorkloadsConfigMapRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import GetUserWorkloadsSecretRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import IPAllocationPolicy -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListEnvironmentsRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListEnvironmentsResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListUserWorkloadsConfigMapsRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListUserWorkloadsConfigMapsResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListUserWorkloadsSecretsRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListUserWorkloadsSecretsResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListWorkloadsRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ListWorkloadsResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import LoadSnapshotRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import LoadSnapshotResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import MaintenanceWindow -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import MasterAuthorizedNetworksConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import NetworkingConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import NodeConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import PollAirflowCommandRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import PollAirflowCommandResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import PrivateClusterConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import PrivateEnvironmentConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import RecoveryConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import RestartWebServerRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import SaveSnapshotRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import SaveSnapshotResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import ScheduledSnapshotsConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import SoftwareConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import StopAirflowCommandRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import StopAirflowCommandResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import StorageConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import TaskLogsRetentionConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import UpdateEnvironmentRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import UpdateUserWorkloadsConfigMapRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import UpdateUserWorkloadsSecretRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import UserWorkloadsConfigMap -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import UserWorkloadsSecret -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import WebServerConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import WebServerNetworkAccessControl -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import WorkloadsConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.image_versions import ImageVersion -from google.cloud.orchestration.airflow.service_v1beta1.types.image_versions import ListImageVersionsRequest -from google.cloud.orchestration.airflow.service_v1beta1.types.image_versions import ListImageVersionsResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.operations import OperationMetadata - -__all__ = ('EnvironmentsClient', - 'EnvironmentsAsyncClient', - 'ImageVersionsClient', - 'ImageVersionsAsyncClient', - 'AirflowMetadataRetentionPolicyConfig', - 'CheckUpgradeRequest', - 'CheckUpgradeResponse', - 'CloudDataLineageIntegration', - 'CreateEnvironmentRequest', - 'CreateUserWorkloadsConfigMapRequest', - 'CreateUserWorkloadsSecretRequest', - 'DatabaseConfig', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'DataRetentionConfig', - 'DeleteEnvironmentRequest', - 'DeleteUserWorkloadsConfigMapRequest', - 'DeleteUserWorkloadsSecretRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'GetEnvironmentRequest', - 'GetUserWorkloadsConfigMapRequest', - 'GetUserWorkloadsSecretRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'ListUserWorkloadsConfigMapsRequest', - 'ListUserWorkloadsConfigMapsResponse', - 'ListUserWorkloadsSecretsRequest', - 'ListUserWorkloadsSecretsResponse', - 'ListWorkloadsRequest', - 'ListWorkloadsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'RestartWebServerRequest', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'StorageConfig', - 'TaskLogsRetentionConfig', - 'UpdateEnvironmentRequest', - 'UpdateUserWorkloadsConfigMapRequest', - 'UpdateUserWorkloadsSecretRequest', - 'UserWorkloadsConfigMap', - 'UserWorkloadsSecret', - 'WebServerConfig', - 'WebServerNetworkAccessControl', - 'WorkloadsConfig', - 'ImageVersion', - 'ListImageVersionsRequest', - 'ListImageVersionsResponse', - 'OperationMetadata', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/gapic_version.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/py.typed b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/py.typed deleted file mode 100644 index a957d7b8dbec..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-orchestration-airflow-service package uses inline types. diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py deleted file mode 100644 index 7b79b2ddb43b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.orchestration.airflow.service_v1beta1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.environments import EnvironmentsClient -from .services.environments import EnvironmentsAsyncClient -from .services.image_versions import ImageVersionsClient -from .services.image_versions import ImageVersionsAsyncClient - -from .types.environments import AirflowMetadataRetentionPolicyConfig -from .types.environments import CheckUpgradeRequest -from .types.environments import CheckUpgradeResponse -from .types.environments import CloudDataLineageIntegration -from .types.environments import CreateEnvironmentRequest -from .types.environments import CreateUserWorkloadsConfigMapRequest -from .types.environments import CreateUserWorkloadsSecretRequest -from .types.environments import DatabaseConfig -from .types.environments import DatabaseFailoverRequest -from .types.environments import DatabaseFailoverResponse -from .types.environments import DataRetentionConfig -from .types.environments import DeleteEnvironmentRequest -from .types.environments import DeleteUserWorkloadsConfigMapRequest -from .types.environments import DeleteUserWorkloadsSecretRequest -from .types.environments import EncryptionConfig -from .types.environments import Environment -from .types.environments import EnvironmentConfig -from .types.environments import ExecuteAirflowCommandRequest -from .types.environments import ExecuteAirflowCommandResponse -from .types.environments import FetchDatabasePropertiesRequest -from .types.environments import FetchDatabasePropertiesResponse -from .types.environments import GetEnvironmentRequest -from .types.environments import GetUserWorkloadsConfigMapRequest -from .types.environments import GetUserWorkloadsSecretRequest -from .types.environments import IPAllocationPolicy -from .types.environments import ListEnvironmentsRequest -from .types.environments import ListEnvironmentsResponse -from .types.environments import ListUserWorkloadsConfigMapsRequest -from .types.environments import ListUserWorkloadsConfigMapsResponse -from .types.environments import ListUserWorkloadsSecretsRequest -from .types.environments import ListUserWorkloadsSecretsResponse -from .types.environments import ListWorkloadsRequest -from .types.environments import ListWorkloadsResponse -from .types.environments import LoadSnapshotRequest -from .types.environments import LoadSnapshotResponse -from .types.environments import MaintenanceWindow -from .types.environments import MasterAuthorizedNetworksConfig -from .types.environments import NetworkingConfig -from .types.environments import NodeConfig -from .types.environments import PollAirflowCommandRequest -from .types.environments import PollAirflowCommandResponse -from .types.environments import PrivateClusterConfig -from .types.environments import PrivateEnvironmentConfig -from .types.environments import RecoveryConfig -from .types.environments import RestartWebServerRequest -from .types.environments import SaveSnapshotRequest -from .types.environments import SaveSnapshotResponse -from .types.environments import ScheduledSnapshotsConfig -from .types.environments import SoftwareConfig -from .types.environments import StopAirflowCommandRequest -from .types.environments import StopAirflowCommandResponse -from .types.environments import StorageConfig -from .types.environments import TaskLogsRetentionConfig -from .types.environments import UpdateEnvironmentRequest -from .types.environments import UpdateUserWorkloadsConfigMapRequest -from .types.environments import UpdateUserWorkloadsSecretRequest -from .types.environments import UserWorkloadsConfigMap -from .types.environments import UserWorkloadsSecret -from .types.environments import WebServerConfig -from .types.environments import WebServerNetworkAccessControl -from .types.environments import WorkloadsConfig -from .types.image_versions import ImageVersion -from .types.image_versions import ListImageVersionsRequest -from .types.image_versions import ListImageVersionsResponse -from .types.operations import OperationMetadata - -__all__ = ( - 'EnvironmentsAsyncClient', - 'ImageVersionsAsyncClient', -'AirflowMetadataRetentionPolicyConfig', -'CheckUpgradeRequest', -'CheckUpgradeResponse', -'CloudDataLineageIntegration', -'CreateEnvironmentRequest', -'CreateUserWorkloadsConfigMapRequest', -'CreateUserWorkloadsSecretRequest', -'DataRetentionConfig', -'DatabaseConfig', -'DatabaseFailoverRequest', -'DatabaseFailoverResponse', -'DeleteEnvironmentRequest', -'DeleteUserWorkloadsConfigMapRequest', -'DeleteUserWorkloadsSecretRequest', -'EncryptionConfig', -'Environment', -'EnvironmentConfig', -'EnvironmentsClient', -'ExecuteAirflowCommandRequest', -'ExecuteAirflowCommandResponse', -'FetchDatabasePropertiesRequest', -'FetchDatabasePropertiesResponse', -'GetEnvironmentRequest', -'GetUserWorkloadsConfigMapRequest', -'GetUserWorkloadsSecretRequest', -'IPAllocationPolicy', -'ImageVersion', -'ImageVersionsClient', -'ListEnvironmentsRequest', -'ListEnvironmentsResponse', -'ListImageVersionsRequest', -'ListImageVersionsResponse', -'ListUserWorkloadsConfigMapsRequest', -'ListUserWorkloadsConfigMapsResponse', -'ListUserWorkloadsSecretsRequest', -'ListUserWorkloadsSecretsResponse', -'ListWorkloadsRequest', -'ListWorkloadsResponse', -'LoadSnapshotRequest', -'LoadSnapshotResponse', -'MaintenanceWindow', -'MasterAuthorizedNetworksConfig', -'NetworkingConfig', -'NodeConfig', -'OperationMetadata', -'PollAirflowCommandRequest', -'PollAirflowCommandResponse', -'PrivateClusterConfig', -'PrivateEnvironmentConfig', -'RecoveryConfig', -'RestartWebServerRequest', -'SaveSnapshotRequest', -'SaveSnapshotResponse', -'ScheduledSnapshotsConfig', -'SoftwareConfig', -'StopAirflowCommandRequest', -'StopAirflowCommandResponse', -'StorageConfig', -'TaskLogsRetentionConfig', -'UpdateEnvironmentRequest', -'UpdateUserWorkloadsConfigMapRequest', -'UpdateUserWorkloadsSecretRequest', -'UserWorkloadsConfigMap', -'UserWorkloadsSecret', -'WebServerConfig', -'WebServerNetworkAccessControl', -'WorkloadsConfig', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json deleted file mode 100644 index f3393a50e431..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,437 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.orchestration.airflow.service_v1beta1", - "protoPackage": "google.cloud.orchestration.airflow.service.v1beta1", - "schema": "1.0", - "services": { - "Environments": { - "clients": { - "grpc": { - "libraryClient": "EnvironmentsClient", - "rpcs": { - "CheckUpgrade": { - "methods": [ - "check_upgrade" - ] - }, - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "CreateUserWorkloadsConfigMap": { - "methods": [ - "create_user_workloads_config_map" - ] - }, - "CreateUserWorkloadsSecret": { - "methods": [ - "create_user_workloads_secret" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "DeleteUserWorkloadsConfigMap": { - "methods": [ - "delete_user_workloads_config_map" - ] - }, - "DeleteUserWorkloadsSecret": { - "methods": [ - "delete_user_workloads_secret" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "GetUserWorkloadsConfigMap": { - "methods": [ - "get_user_workloads_config_map" - ] - }, - "GetUserWorkloadsSecret": { - "methods": [ - "get_user_workloads_secret" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "ListUserWorkloadsConfigMaps": { - "methods": [ - "list_user_workloads_config_maps" - ] - }, - "ListUserWorkloadsSecrets": { - "methods": [ - "list_user_workloads_secrets" - ] - }, - "ListWorkloads": { - "methods": [ - "list_workloads" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "RestartWebServer": { - "methods": [ - "restart_web_server" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - }, - "UpdateUserWorkloadsConfigMap": { - "methods": [ - "update_user_workloads_config_map" - ] - }, - "UpdateUserWorkloadsSecret": { - "methods": [ - "update_user_workloads_secret" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EnvironmentsAsyncClient", - "rpcs": { - "CheckUpgrade": { - "methods": [ - "check_upgrade" - ] - }, - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "CreateUserWorkloadsConfigMap": { - "methods": [ - "create_user_workloads_config_map" - ] - }, - "CreateUserWorkloadsSecret": { - "methods": [ - "create_user_workloads_secret" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "DeleteUserWorkloadsConfigMap": { - "methods": [ - "delete_user_workloads_config_map" - ] - }, - "DeleteUserWorkloadsSecret": { - "methods": [ - "delete_user_workloads_secret" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "GetUserWorkloadsConfigMap": { - "methods": [ - "get_user_workloads_config_map" - ] - }, - "GetUserWorkloadsSecret": { - "methods": [ - "get_user_workloads_secret" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "ListUserWorkloadsConfigMaps": { - "methods": [ - "list_user_workloads_config_maps" - ] - }, - "ListUserWorkloadsSecrets": { - "methods": [ - "list_user_workloads_secrets" - ] - }, - "ListWorkloads": { - "methods": [ - "list_workloads" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "RestartWebServer": { - "methods": [ - "restart_web_server" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - }, - "UpdateUserWorkloadsConfigMap": { - "methods": [ - "update_user_workloads_config_map" - ] - }, - "UpdateUserWorkloadsSecret": { - "methods": [ - "update_user_workloads_secret" - ] - } - } - }, - "rest": { - "libraryClient": "EnvironmentsClient", - "rpcs": { - "CheckUpgrade": { - "methods": [ - "check_upgrade" - ] - }, - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "CreateUserWorkloadsConfigMap": { - "methods": [ - "create_user_workloads_config_map" - ] - }, - "CreateUserWorkloadsSecret": { - "methods": [ - "create_user_workloads_secret" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "DeleteUserWorkloadsConfigMap": { - "methods": [ - "delete_user_workloads_config_map" - ] - }, - "DeleteUserWorkloadsSecret": { - "methods": [ - "delete_user_workloads_secret" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "GetUserWorkloadsConfigMap": { - "methods": [ - "get_user_workloads_config_map" - ] - }, - "GetUserWorkloadsSecret": { - "methods": [ - "get_user_workloads_secret" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "ListUserWorkloadsConfigMaps": { - "methods": [ - "list_user_workloads_config_maps" - ] - }, - "ListUserWorkloadsSecrets": { - "methods": [ - "list_user_workloads_secrets" - ] - }, - "ListWorkloads": { - "methods": [ - "list_workloads" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "RestartWebServer": { - "methods": [ - "restart_web_server" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - }, - "UpdateUserWorkloadsConfigMap": { - "methods": [ - "update_user_workloads_config_map" - ] - }, - "UpdateUserWorkloadsSecret": { - "methods": [ - "update_user_workloads_secret" - ] - } - } - } - } - }, - "ImageVersions": { - "clients": { - "grpc": { - "libraryClient": "ImageVersionsClient", - "rpcs": { - "ListImageVersions": { - "methods": [ - "list_image_versions" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ImageVersionsAsyncClient", - "rpcs": { - "ListImageVersions": { - "methods": [ - "list_image_versions" - ] - } - } - }, - "rest": { - "libraryClient": "ImageVersionsClient", - "rpcs": { - "ListImageVersions": { - "methods": [ - "list_image_versions" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/py.typed b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/py.typed deleted file mode 100644 index a957d7b8dbec..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-orchestration-airflow-service package uses inline types. diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/__init__.py deleted file mode 100644 index 8aea3f820923..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/__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 EnvironmentsClient -from .async_client import EnvironmentsAsyncClient - -__all__ = ( - 'EnvironmentsClient', - 'EnvironmentsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py deleted file mode 100644 index 0a9a29c0f361..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py +++ /dev/null @@ -1,3350 +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.orchestration.airflow.service_v1beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_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.orchestration.airflow.service_v1beta1.services.environments import pagers -from google.cloud.orchestration.airflow.service_v1beta1.types import environments -from google.cloud.orchestration.airflow.service_v1beta1.types import operations -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 EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .client import EnvironmentsClient - -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 EnvironmentsAsyncClient: - """Managed Apache Airflow Environments.""" - - _client: EnvironmentsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = EnvironmentsClient._DEFAULT_UNIVERSE - - environment_path = staticmethod(EnvironmentsClient.environment_path) - parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) - user_workloads_config_map_path = staticmethod(EnvironmentsClient.user_workloads_config_map_path) - parse_user_workloads_config_map_path = staticmethod(EnvironmentsClient.parse_user_workloads_config_map_path) - user_workloads_secret_path = staticmethod(EnvironmentsClient.user_workloads_secret_path) - parse_user_workloads_secret_path = staticmethod(EnvironmentsClient.parse_user_workloads_secret_path) - common_billing_account_path = staticmethod(EnvironmentsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EnvironmentsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) - parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) - common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) - parse_common_organization_path = staticmethod(EnvironmentsClient.parse_common_organization_path) - common_project_path = staticmethod(EnvironmentsClient.common_project_path) - parse_common_project_path = staticmethod(EnvironmentsClient.parse_common_project_path) - common_location_path = staticmethod(EnvironmentsClient.common_location_path) - parse_common_location_path = staticmethod(EnvironmentsClient.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: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_info.__func__(EnvironmentsAsyncClient, 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: - EnvironmentsAsyncClient: The constructed client. - """ - return EnvironmentsClient.from_service_account_file.__func__(EnvironmentsAsyncClient, 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 EnvironmentsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EnvironmentsTransport: - """Returns the transport used by the client instance. - - Returns: - EnvironmentsTransport: 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 = EnvironmentsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EnvironmentsTransport, Callable[..., EnvironmentsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the environments 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,EnvironmentsTransport,Callable[..., EnvironmentsTransport]]]): - 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 EnvironmentsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = EnvironmentsClient( - 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.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient`.", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "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.orchestration.airflow.service.v1beta1.Environments", - "credentialsType": None, - } - ) - - async def create_environment(self, - request: Optional[Union[environments.CreateEnvironmentRequest, dict]] = None, - *, - parent: Optional[str] = None, - environment: Optional[environments.Environment] = 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"""Create a new environment. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_create_environment(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateEnvironmentRequest( - ) - - # Make the request - operation = client.create_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateEnvironmentRequest, dict]]): - The request object. Create a new environment. - parent (:class:`str`): - The parent must be of the form - "projects/{projectId}/locations/{locationId}". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.Environment`): - The environment to create. - This corresponds to the ``environment`` 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.orchestration.airflow.service_v1beta1.types.Environment` - An environment for running orchestration tasks. - - """ - # 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. - flattened_params = [parent, environment] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateEnvironmentRequest): - request = environments.CreateEnvironmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if environment is not None: - request.environment = environment - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_environment] - - # 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, - environments.Environment, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_environment(self, - request: Optional[Union[environments.GetEnvironmentRequest, 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]]] = (), - ) -> environments.Environment: - r"""Get an existing environment. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_get_environment(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.GetEnvironmentRequest( - ) - - # Make the request - response = await client.get_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest, dict]]): - The request object. Get an environment. - name (:class:`str`): - The resource name of the environment - to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1beta1.types.Environment: - An environment for running - orchestration tasks. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetEnvironmentRequest): - request = environments.GetEnvironmentRequest(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_environment] - - # 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_environments(self, - request: Optional[Union[environments.ListEnvironmentsRequest, 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.ListEnvironmentsAsyncPager: - r"""List environments. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_list_environments(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ListEnvironmentsRequest( - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest, dict]]): - The request object. List environments in a project and - location. - parent (:class:`str`): - List environments in the given - project and location, in the form: - "projects/{projectId}/locations/{locationId}" - - 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsAsyncPager: - The environments in a project and - location. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListEnvironmentsRequest): - request = environments.ListEnvironmentsRequest(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_environments] - - # 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.ListEnvironmentsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_environment(self, - request: Optional[Union[environments.UpdateEnvironmentRequest, dict]] = None, - *, - name: Optional[str] = None, - environment: Optional[environments.Environment] = 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"""Update an environment. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_update_environment(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateEnvironmentRequest( - ) - - # Make the request - operation = client.update_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateEnvironmentRequest, dict]]): - The request object. Update an environment. - name (:class:`str`): - The relative resource name of the - environment to update, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.Environment`): - A patch environment. Fields specified by the - ``updateMask`` will be copied from the patch environment - into the environment under update. - - This corresponds to the ``environment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. A comma-separated list of paths, relative to - ``Environment``, of fields to update. For example, to - set the version of scikit-learn to install in the - environment to 0.19.0 and to remove an existing - installation of argparse, the ``updateMask`` parameter - would include the following two ``paths`` values: - "config.softwareConfig.pypiPackages.scikit-learn" and - "config.softwareConfig.pypiPackages.argparse". The - included patch environment would specify the - scikit-learn version as follows: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "scikit-learn":"==0.19.0" - } - } - } - } - - Note that in the above example, any existing PyPI - packages other than scikit-learn and argparse will be - unaffected. - - Only one update type may be included in a single - request's ``updateMask``. For example, one cannot update - both the PyPI packages and labels in the same request. - However, it is possible to update multiple members of a - map field simultaneously in the same request. For - example, to set the labels "label1" and "label2" while - clearing "label3" (assuming it already exists), one can - provide the paths "labels.label1", "labels.label2", and - "labels.label3" and populate the patch environment as - follows: - - :: - - { - "labels":{ - "label1":"new-label1-value" - "label2":"new-label2-value" - } - } - - Note that in the above example, any existing labels that - are not included in the ``updateMask`` will be - unaffected. - - It is also possible to replace an entire map field by - providing the map field's path in the ``updateMask``. - The new value of the field will be that which is - provided in the patch environment. For example, to - delete all pre-existing user-specified PyPI packages and - install botocore at version 1.7.14, the ``updateMask`` - would contain the path - "config.softwareConfig.pypiPackages", and the patch - environment would be the following: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "botocore":"==1.7.14" - } - } - } - } - - **Note:** Only the following fields can be updated: - - - ``config.softwareConfig.pypiPackages`` - - - Replace all custom custom PyPI packages. If a - replacement package map is not included in - ``environment``, all custom PyPI packages are - cleared. It is an error to provide both this mask - and a mask specifying an individual package. - - - ``config.softwareConfig.pypiPackages.``\ packagename - - - Update the custom PyPI package *packagename*, - preserving other packages. To delete the package, - include it in ``updateMask``, and omit the mapping - for it in - ``environment.config.softwareConfig.pypiPackages``. - It is an error to provide both a mask of this form - and the ``config.softwareConfig.pypiPackages`` - mask. - - - ``labels`` - - - Replace all environment labels. If a replacement - labels map is not included in ``environment``, all - labels are cleared. It is an error to provide both - this mask and a mask specifying one or more - individual labels. - - - ``labels.``\ labelName - - - Set the label named *labelName*, while preserving - other labels. To delete the label, include it in - ``updateMask`` and omit its mapping in - ``environment.labels``. It is an error to provide - both a mask of this form and the ``labels`` mask. - - - ``config.nodeCount`` - - - Horizontally scale the number of nodes in the - environment. An integer greater than or equal to 3 - must be provided in the ``config.nodeCount`` - field. Supported for Cloud Composer environments - in versions composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerNetworkAccessControl`` - - - Replace the environment's current - WebServerNetworkAccessControl. - - - ``config.softwareConfig.airflowConfigOverrides`` - - - Replace all Apache Airflow config overrides. If a - replacement config overrides map is not included - in ``environment``, all config overrides are - cleared. It is an error to provide both this mask - and a mask specifying one or more individual - config overrides. - - - ``config.softwareConfig.airflowConfigOverrides.``\ section-name - - - Override the Apache Airflow config property *name* - in the section named *section*, preserving other - properties. To delete the property override, - include it in ``updateMask`` and omit its mapping - in - ``environment.config.softwareConfig.airflowConfigOverrides``. - It is an error to provide both a mask of this form - and the - ``config.softwareConfig.airflowConfigOverrides`` - mask. - - - ``config.softwareConfig.envVariables`` - - - Replace all environment variables. If a - replacement environment variable map is not - included in ``environment``, all custom - environment variables are cleared. - - - ``config.softwareConfig.imageVersion`` - - - Upgrade the version of the environment in-place. - Refer to ``SoftwareConfig.image_version`` for - information on how to format the new image - version. Additionally, the new image version - cannot effect a version downgrade, and must match - the current image version's Composer and Airflow - major versions. Consult the `Cloud Composer - version - list `__ - for valid values. - - - ``config.softwareConfig.schedulerCount`` - - - Horizontally scale the number of schedulers in - Airflow. A positive integer not greater than the - number of nodes must be provided in the - ``config.softwareConfig.schedulerCount`` field. - Supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-2.*.*. - - - ``config.softwareConfig.cloudDataLineageIntegration`` - - - Configuration for Cloud Data Lineage integration. - - - ``config.databaseConfig.machineType`` - - - Cloud SQL machine type used by Airflow database. - It has to be one of: db-n1-standard-2, - db-n1-standard-4, db-n1-standard-8 or - db-n1-standard-16. Supported for Cloud Composer - environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerConfig.machineType`` - - - Machine type on which Airflow web server is - running. It has to be one of: - composer-n1-webserver-2, composer-n1-webserver-4 - or composer-n1-webserver-8. Supported for Cloud - Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.maintenanceWindow`` - - - Maintenance window during which Cloud Composer - components may be under maintenance. - - - ``config.workloadsConfig`` - - - The workloads configuration settings for the GKE - cluster associated with the Cloud Composer - environment. Supported for Cloud Composer - environments in versions - composer-2.\ *.*-airflow-*.*.\* and newer. - - - ``config.environmentSize`` - - - The size of the Cloud Composer environment. - Supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and - newer. - - 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.orchestration.airflow.service_v1beta1.types.Environment` - An environment for running orchestration tasks. - - """ - # 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. - flattened_params = [name, environment, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateEnvironmentRequest): - request = environments.UpdateEnvironmentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if environment is not None: - request.environment = environment - 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_environment] - - # 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, - environments.Environment, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_environment(self, - request: Optional[Union[environments.DeleteEnvironmentRequest, 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"""Delete an environment. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_delete_environment(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteEnvironmentRequest( - ) - - # Make the request - operation = client.delete_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteEnvironmentRequest, dict]]): - The request object. Delete an environment. - name (:class:`str`): - The environment to delete, in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteEnvironmentRequest): - request = environments.DeleteEnvironmentRequest(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_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def restart_web_server(self, - request: Optional[Union[environments.RestartWebServerRequest, dict]] = 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"""Restart Airflow web server. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_restart_web_server(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.RestartWebServerRequest( - ) - - # Make the request - operation = client.restart_web_server(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest, dict]]): - The request object. Restart Airflow web server. - 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.orchestration.airflow.service_v1beta1.types.Environment` - An environment for running orchestration tasks. - - """ - # 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, environments.RestartWebServerRequest): - request = environments.RestartWebServerRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.restart_web_server] - - # 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, - environments.Environment, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def check_upgrade(self, - request: Optional[Union[environments.CheckUpgradeRequest, dict]] = 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"""Check if an upgrade operation on the environment will - succeed. - In case of problems detailed info can be found in the - returned 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.orchestration.airflow import service_v1beta1 - - async def sample_check_upgrade(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.CheckUpgradeRequest( - ) - - # Make the request - operation = client.check_upgrade(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeRequest, dict]]): - The request object. Request to check whether image - upgrade will succeed. - 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.orchestration.airflow.service_v1beta1.types.CheckUpgradeResponse` Message containing information about the result of an upgrade check - operation. - - """ - # 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, environments.CheckUpgradeRequest): - request = environments.CheckUpgradeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.check_upgrade] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.CheckUpgradeResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def execute_airflow_command(self, - request: Optional[Union[environments.ExecuteAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.ExecuteAirflowCommandResponse: - r"""Executes Airflow CLI command. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_execute_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ExecuteAirflowCommandRequest( - ) - - # Make the request - response = await client.execute_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandRequest, dict]]): - The request object. Execute Airflow Command request. - 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.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandResponse: - Response to - ExecuteAirflowCommandRequest. - - """ - # 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, environments.ExecuteAirflowCommandRequest): - request = environments.ExecuteAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.execute_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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 stop_airflow_command(self, - request: Optional[Union[environments.StopAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.StopAirflowCommandResponse: - r"""Stops Airflow CLI command execution. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_stop_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.StopAirflowCommandRequest( - ) - - # Make the request - response = await client.stop_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest, dict]]): - The request object. Stop Airflow Command request. - 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.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse: - Response to - StopAirflowCommandRequest. - - """ - # 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, environments.StopAirflowCommandRequest): - request = environments.StopAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.stop_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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 poll_airflow_command(self, - request: Optional[Union[environments.PollAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.PollAirflowCommandResponse: - r"""Polls Airflow CLI command execution and fetches logs. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_poll_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.PollAirflowCommandRequest( - ) - - # Make the request - response = await client.poll_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest, dict]]): - The request object. Poll Airflow Command request. - 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.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse: - Response to - PollAirflowCommandRequest. - - """ - # 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, environments.PollAirflowCommandRequest): - request = environments.PollAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.poll_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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_workloads(self, - request: Optional[Union[environments.ListWorkloadsRequest, 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.ListWorkloadsAsyncPager: - r"""Lists workloads in a Cloud Composer environment. Workload is a - unit that runs a single Composer component. - - This method is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_list_workloads(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ListWorkloadsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workloads(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest, dict]]): - The request object. Request for listing workloads in a - Cloud Composer environment. - parent (:class:`str`): - Required. The environment name to get - workloads for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListWorkloadsAsyncPager: - Response to ListWorkloadsRequest. - - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListWorkloadsRequest): - request = environments.ListWorkloadsRequest(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_workloads] - - # 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.ListWorkloadsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_user_workloads_secret(self, - request: Optional[Union[environments.CreateUserWorkloadsSecretRequest, dict]] = None, - *, - parent: Optional[str] = None, - user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_create_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateUserWorkloadsSecretRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsSecretRequest, dict]]): - The request object. Create user workloads Secret request. - parent (:class:`str`): - Required. The environment name to - create a Secret for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_workloads_secret (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret`): - Required. User workloads Secret to - create. - - This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [parent, user_workloads_secret] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateUserWorkloadsSecretRequest): - request = environments.CreateUserWorkloadsSecretRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_workloads_secret is not None: - request.user_workloads_secret = user_workloads_secret - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_user_workloads_secret] - - # 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 get_user_workloads_secret(self, - request: Optional[Union[environments.GetUserWorkloadsSecretRequest, 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]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Gets an existing user workloads Secret. Values of the "data" - field in the response are cleared. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_get_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.GetUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsSecretRequest, dict]]): - The request object. Get user workloads Secret request. - name (:class:`str`): - Required. The resource name of the - Secret to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" - - 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetUserWorkloadsSecretRequest): - request = environments.GetUserWorkloadsSecretRequest(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_user_workloads_secret] - - # 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_user_workloads_secrets(self, - request: Optional[Union[environments.ListUserWorkloadsSecretsRequest, 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.ListUserWorkloadsSecretsAsyncPager: - r"""Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_list_user_workloads_secrets(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ListUserWorkloadsSecretsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_secrets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest, dict]]): - The request object. List user workloads Secrets request. - parent (:class:`str`): - Required. List Secrets in the given - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsSecretsAsyncPager: - The user workloads Secrets for a - given environment. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListUserWorkloadsSecretsRequest): - request = environments.ListUserWorkloadsSecretsRequest(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_user_workloads_secrets] - - # 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.ListUserWorkloadsSecretsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_user_workloads_secret(self, - request: Optional[Union[environments.UpdateUserWorkloadsSecretRequest, dict]] = None, - *, - user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_update_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateUserWorkloadsSecretRequest( - ) - - # Make the request - response = await client.update_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsSecretRequest, dict]]): - The request object. Update user workloads Secret request. - user_workloads_secret (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret`): - Optional. User workloads Secret to - override. - - This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [user_workloads_secret] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateUserWorkloadsSecretRequest): - request = environments.UpdateUserWorkloadsSecretRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if user_workloads_secret is not None: - request.user_workloads_secret = user_workloads_secret - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_user_workloads_secret] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user_workloads_secret.name", request.user_workloads_secret.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_user_workloads_secret(self, - request: Optional[Union[environments.DeleteUserWorkloadsSecretRequest, 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]]] = (), - ) -> None: - r"""Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_delete_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - await client.delete_user_workloads_secret(request=request) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsSecretRequest, dict]]): - The request object. Delete user workloads Secret request. - name (:class:`str`): - Required. The Secret to delete, in - the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" - - 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`. - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteUserWorkloadsSecretRequest): - request = environments.DeleteUserWorkloadsSecretRequest(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_user_workloads_secret] - - # 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 create_user_workloads_config_map(self, - request: Optional[Union[environments.CreateUserWorkloadsConfigMapRequest, dict]] = None, - *, - parent: Optional[str] = None, - user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_create_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateUserWorkloadsConfigMapRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsConfigMapRequest, dict]]): - The request object. Create user workloads ConfigMap - request. - parent (:class:`str`): - Required. The environment name to - create a ConfigMap for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_workloads_config_map (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap`): - Required. User workloads ConfigMap to - create. - - This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [parent, user_workloads_config_map] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateUserWorkloadsConfigMapRequest): - request = environments.CreateUserWorkloadsConfigMapRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_workloads_config_map is not None: - request.user_workloads_config_map = user_workloads_config_map - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_user_workloads_config_map] - - # 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 get_user_workloads_config_map(self, - request: Optional[Union[environments.GetUserWorkloadsConfigMapRequest, 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]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_get_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.GetUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsConfigMapRequest, dict]]): - The request object. Get user workloads ConfigMap request. - name (:class:`str`): - Required. The resource name of the - ConfigMap to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" - - 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetUserWorkloadsConfigMapRequest): - request = environments.GetUserWorkloadsConfigMapRequest(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_user_workloads_config_map] - - # 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_user_workloads_config_maps(self, - request: Optional[Union[environments.ListUserWorkloadsConfigMapsRequest, 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.ListUserWorkloadsConfigMapsAsyncPager: - r"""Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_list_user_workloads_config_maps(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ListUserWorkloadsConfigMapsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_config_maps(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest, dict]]): - The request object. List user workloads ConfigMaps - request. - parent (:class:`str`): - Required. List ConfigMaps in the - given environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsConfigMapsAsyncPager: - The user workloads ConfigMaps for a - given environment. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListUserWorkloadsConfigMapsRequest): - request = environments.ListUserWorkloadsConfigMapsRequest(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_user_workloads_config_maps] - - # 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.ListUserWorkloadsConfigMapsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_user_workloads_config_map(self, - request: Optional[Union[environments.UpdateUserWorkloadsConfigMapRequest, dict]] = None, - *, - user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_update_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateUserWorkloadsConfigMapRequest( - ) - - # Make the request - response = await client.update_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsConfigMapRequest, dict]]): - The request object. Update user workloads ConfigMap - request. - user_workloads_config_map (:class:`google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap`): - Optional. User workloads ConfigMap to - override. - - This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [user_workloads_config_map] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateUserWorkloadsConfigMapRequest): - request = environments.UpdateUserWorkloadsConfigMapRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if user_workloads_config_map is not None: - request.user_workloads_config_map = user_workloads_config_map - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_user_workloads_config_map] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user_workloads_config_map.name", request.user_workloads_config_map.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_user_workloads_config_map(self, - request: Optional[Union[environments.DeleteUserWorkloadsConfigMapRequest, 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]]] = (), - ) -> None: - r"""Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_delete_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - await client.delete_user_workloads_config_map(request=request) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsConfigMapRequest, dict]]): - The request object. Delete user workloads ConfigMap - request. - name (:class:`str`): - Required. The ConfigMap to delete, in - the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" - - 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`. - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteUserWorkloadsConfigMapRequest): - request = environments.DeleteUserWorkloadsConfigMapRequest(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_user_workloads_config_map] - - # 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 save_snapshot(self, - request: Optional[Union[environments.SaveSnapshotRequest, dict]] = 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 snapshots of a Cloud Composer environment. - - As a result of this operation, snapshot of environment's - state is stored in a location specified in the - SaveSnapshotRequest. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_save_snapshot(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.SaveSnapshotRequest( - ) - - # Make the request - operation = client.save_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest, dict]]): - The request object. Request to create a snapshot of a - Cloud Composer environment. - 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.orchestration.airflow.service_v1beta1.types.SaveSnapshotResponse` - Response to SaveSnapshotRequest. - - """ - # 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, environments.SaveSnapshotRequest): - request = environments.SaveSnapshotRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.save_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.SaveSnapshotResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def load_snapshot(self, - request: Optional[Union[environments.LoadSnapshotRequest, dict]] = 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"""Loads a snapshot of a Cloud Composer environment. - - As a result of this operation, a snapshot of - environment's specified in LoadSnapshotRequest is loaded - into the environment. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_load_snapshot(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.LoadSnapshotRequest( - ) - - # Make the request - operation = client.load_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest, dict]]): - The request object. Request to load a snapshot into a - Cloud Composer environment. - 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.orchestration.airflow.service_v1beta1.types.LoadSnapshotResponse` - Response to LoadSnapshotRequest. - - """ - # 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, environments.LoadSnapshotRequest): - request = environments.LoadSnapshotRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.load_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.LoadSnapshotResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def database_failover(self, - request: Optional[Union[environments.DatabaseFailoverRequest, dict]] = 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"""Triggers database failover (only for highly resilient - environments). - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_database_failover(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.DatabaseFailoverRequest( - ) - - # Make the request - operation = client.database_failover(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseFailoverRequest, dict]]): - The request object. Request to trigger database failover - (only for highly resilient - environments). - 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.orchestration.airflow.service_v1beta1.types.DatabaseFailoverResponse` - Response for DatabaseFailoverRequest. - - """ - # 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, environments.DatabaseFailoverRequest): - request = environments.DatabaseFailoverRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.database_failover] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.DatabaseFailoverResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - async def fetch_database_properties(self, - request: Optional[Union[environments.FetchDatabasePropertiesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.FetchDatabasePropertiesResponse: - r"""Fetches database properties. - - .. 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.orchestration.airflow import service_v1beta1 - - async def sample_fetch_database_properties(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.FetchDatabasePropertiesRequest( - environment="environment_value", - ) - - # Make the request - response = await client.fetch_database_properties(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesRequest, dict]]): - The request object. Request to fetch properties of - environment's database. - 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.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesResponse: - Response for - FetchDatabasePropertiesRequest. - - """ - # 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, environments.FetchDatabasePropertiesRequest): - request = environments.FetchDatabasePropertiesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.fetch_database_properties] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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 __aenter__(self) -> "EnvironmentsAsyncClient": - 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__ = ( - "EnvironmentsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py deleted file mode 100644 index 625e3b410151..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py +++ /dev/null @@ -1,3723 +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 http import HTTPStatus -import json -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.orchestration.airflow.service_v1beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, 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.orchestration.airflow.service_v1beta1.services.environments import pagers -from google.cloud.orchestration.airflow.service_v1beta1.types import environments -from google.cloud.orchestration.airflow.service_v1beta1.types import operations -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 EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EnvironmentsGrpcTransport -from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .transports.rest import EnvironmentsRestTransport - - -class EnvironmentsClientMeta(type): - """Metaclass for the Environments 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[EnvironmentsTransport]] - _transport_registry["grpc"] = EnvironmentsGrpcTransport - _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport - _transport_registry["rest"] = EnvironmentsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EnvironmentsTransport]: - """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 EnvironmentsClient(metaclass=EnvironmentsClientMeta): - """Managed Apache Airflow Environments.""" - - @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 = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "composer.{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: - EnvironmentsClient: 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: - EnvironmentsClient: 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) -> EnvironmentsTransport: - """Returns the transport used by the client instance. - - Returns: - EnvironmentsTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def environment_path(project: str,location: str,environment: str,) -> str: - """Returns a fully-qualified environment string.""" - return "projects/{project}/locations/{location}/environments/{environment}".format(project=project, location=location, environment=environment, ) - - @staticmethod - def parse_environment_path(path: str) -> Dict[str,str]: - """Parses a environment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def user_workloads_config_map_path(project: str,location: str,environment: str,user_workloads_config_map: str,) -> str: - """Returns a fully-qualified user_workloads_config_map string.""" - return "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsConfigMaps/{user_workloads_config_map}".format(project=project, location=location, environment=environment, user_workloads_config_map=user_workloads_config_map, ) - - @staticmethod - def parse_user_workloads_config_map_path(path: str) -> Dict[str,str]: - """Parses a user_workloads_config_map path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)/userWorkloadsConfigMaps/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def user_workloads_secret_path(project: str,location: str,environment: str,user_workloads_secret: str,) -> str: - """Returns a fully-qualified user_workloads_secret string.""" - return "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsSecrets/{user_workloads_secret}".format(project=project, location=location, environment=environment, user_workloads_secret=user_workloads_secret, ) - - @staticmethod - def parse_user_workloads_secret_path(path: str) -> Dict[str,str]: - """Parses a user_workloads_secret path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/environments/(?P.+?)/userWorkloadsSecrets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = EnvironmentsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = EnvironmentsClient._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 = EnvironmentsClient._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 - - def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError - ) -> None: - """Adds credential info string to error details for 401/403/404 errors. - - Args: - error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. - """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @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, EnvironmentsTransport, Callable[..., EnvironmentsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the environments 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,EnvironmentsTransport,Callable[..., EnvironmentsTransport]]]): - 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 EnvironmentsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = EnvironmentsClient._read_environment_variables() - self._client_cert_source = EnvironmentsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = EnvironmentsClient._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, EnvironmentsTransport) - if transport_provided: - # transport is a EnvironmentsTransport 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(EnvironmentsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - EnvironmentsClient._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[EnvironmentsTransport], Callable[..., EnvironmentsTransport]] = ( - EnvironmentsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., EnvironmentsTransport], 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.orchestration.airflow.service_v1beta1.EnvironmentsClient`.", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "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.orchestration.airflow.service.v1beta1.Environments", - "credentialsType": None, - } - ) - - def create_environment(self, - request: Optional[Union[environments.CreateEnvironmentRequest, dict]] = None, - *, - parent: Optional[str] = None, - environment: Optional[environments.Environment] = 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"""Create a new environment. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_create_environment(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateEnvironmentRequest( - ) - - # Make the request - operation = client.create_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateEnvironmentRequest, dict]): - The request object. Create a new environment. - parent (str): - The parent must be of the form - "projects/{projectId}/locations/{locationId}". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (google.cloud.orchestration.airflow.service_v1beta1.types.Environment): - The environment to create. - This corresponds to the ``environment`` 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.orchestration.airflow.service_v1beta1.types.Environment` - An environment for running orchestration tasks. - - """ - # 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. - flattened_params = [parent, environment] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateEnvironmentRequest): - request = environments.CreateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if environment is not None: - request.environment = environment - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_environment] - - # 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, - environments.Environment, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_environment(self, - request: Optional[Union[environments.GetEnvironmentRequest, 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]]] = (), - ) -> environments.Environment: - r"""Get an existing environment. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_get_environment(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.GetEnvironmentRequest( - ) - - # Make the request - response = client.get_environment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest, dict]): - The request object. Get an environment. - name (str): - The resource name of the environment - to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1beta1.types.Environment: - An environment for running - orchestration tasks. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetEnvironmentRequest): - request = environments.GetEnvironmentRequest(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_environment] - - # 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_environments(self, - request: Optional[Union[environments.ListEnvironmentsRequest, 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.ListEnvironmentsPager: - r"""List environments. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_list_environments(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.ListEnvironmentsRequest( - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest, dict]): - The request object. List environments in a project and - location. - parent (str): - List environments in the given - project and location, in the form: - "projects/{projectId}/locations/{locationId}" - - 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsPager: - The environments in a project and - location. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListEnvironmentsRequest): - request = environments.ListEnvironmentsRequest(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_environments] - - # 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.ListEnvironmentsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_environment(self, - request: Optional[Union[environments.UpdateEnvironmentRequest, dict]] = None, - *, - name: Optional[str] = None, - environment: Optional[environments.Environment] = 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"""Update an environment. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_update_environment(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateEnvironmentRequest( - ) - - # Make the request - operation = client.update_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateEnvironmentRequest, dict]): - The request object. Update an environment. - name (str): - The relative resource name of the - environment to update, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - environment (google.cloud.orchestration.airflow.service_v1beta1.types.Environment): - A patch environment. Fields specified by the - ``updateMask`` will be copied from the patch environment - into the environment under update. - - This corresponds to the ``environment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A comma-separated list of paths, relative to - ``Environment``, of fields to update. For example, to - set the version of scikit-learn to install in the - environment to 0.19.0 and to remove an existing - installation of argparse, the ``updateMask`` parameter - would include the following two ``paths`` values: - "config.softwareConfig.pypiPackages.scikit-learn" and - "config.softwareConfig.pypiPackages.argparse". The - included patch environment would specify the - scikit-learn version as follows: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "scikit-learn":"==0.19.0" - } - } - } - } - - Note that in the above example, any existing PyPI - packages other than scikit-learn and argparse will be - unaffected. - - Only one update type may be included in a single - request's ``updateMask``. For example, one cannot update - both the PyPI packages and labels in the same request. - However, it is possible to update multiple members of a - map field simultaneously in the same request. For - example, to set the labels "label1" and "label2" while - clearing "label3" (assuming it already exists), one can - provide the paths "labels.label1", "labels.label2", and - "labels.label3" and populate the patch environment as - follows: - - :: - - { - "labels":{ - "label1":"new-label1-value" - "label2":"new-label2-value" - } - } - - Note that in the above example, any existing labels that - are not included in the ``updateMask`` will be - unaffected. - - It is also possible to replace an entire map field by - providing the map field's path in the ``updateMask``. - The new value of the field will be that which is - provided in the patch environment. For example, to - delete all pre-existing user-specified PyPI packages and - install botocore at version 1.7.14, the ``updateMask`` - would contain the path - "config.softwareConfig.pypiPackages", and the patch - environment would be the following: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "botocore":"==1.7.14" - } - } - } - } - - **Note:** Only the following fields can be updated: - - - ``config.softwareConfig.pypiPackages`` - - - Replace all custom custom PyPI packages. If a - replacement package map is not included in - ``environment``, all custom PyPI packages are - cleared. It is an error to provide both this mask - and a mask specifying an individual package. - - - ``config.softwareConfig.pypiPackages.``\ packagename - - - Update the custom PyPI package *packagename*, - preserving other packages. To delete the package, - include it in ``updateMask``, and omit the mapping - for it in - ``environment.config.softwareConfig.pypiPackages``. - It is an error to provide both a mask of this form - and the ``config.softwareConfig.pypiPackages`` - mask. - - - ``labels`` - - - Replace all environment labels. If a replacement - labels map is not included in ``environment``, all - labels are cleared. It is an error to provide both - this mask and a mask specifying one or more - individual labels. - - - ``labels.``\ labelName - - - Set the label named *labelName*, while preserving - other labels. To delete the label, include it in - ``updateMask`` and omit its mapping in - ``environment.labels``. It is an error to provide - both a mask of this form and the ``labels`` mask. - - - ``config.nodeCount`` - - - Horizontally scale the number of nodes in the - environment. An integer greater than or equal to 3 - must be provided in the ``config.nodeCount`` - field. Supported for Cloud Composer environments - in versions composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerNetworkAccessControl`` - - - Replace the environment's current - WebServerNetworkAccessControl. - - - ``config.softwareConfig.airflowConfigOverrides`` - - - Replace all Apache Airflow config overrides. If a - replacement config overrides map is not included - in ``environment``, all config overrides are - cleared. It is an error to provide both this mask - and a mask specifying one or more individual - config overrides. - - - ``config.softwareConfig.airflowConfigOverrides.``\ section-name - - - Override the Apache Airflow config property *name* - in the section named *section*, preserving other - properties. To delete the property override, - include it in ``updateMask`` and omit its mapping - in - ``environment.config.softwareConfig.airflowConfigOverrides``. - It is an error to provide both a mask of this form - and the - ``config.softwareConfig.airflowConfigOverrides`` - mask. - - - ``config.softwareConfig.envVariables`` - - - Replace all environment variables. If a - replacement environment variable map is not - included in ``environment``, all custom - environment variables are cleared. - - - ``config.softwareConfig.imageVersion`` - - - Upgrade the version of the environment in-place. - Refer to ``SoftwareConfig.image_version`` for - information on how to format the new image - version. Additionally, the new image version - cannot effect a version downgrade, and must match - the current image version's Composer and Airflow - major versions. Consult the `Cloud Composer - version - list `__ - for valid values. - - - ``config.softwareConfig.schedulerCount`` - - - Horizontally scale the number of schedulers in - Airflow. A positive integer not greater than the - number of nodes must be provided in the - ``config.softwareConfig.schedulerCount`` field. - Supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-2.*.*. - - - ``config.softwareConfig.cloudDataLineageIntegration`` - - - Configuration for Cloud Data Lineage integration. - - - ``config.databaseConfig.machineType`` - - - Cloud SQL machine type used by Airflow database. - It has to be one of: db-n1-standard-2, - db-n1-standard-4, db-n1-standard-8 or - db-n1-standard-16. Supported for Cloud Composer - environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerConfig.machineType`` - - - Machine type on which Airflow web server is - running. It has to be one of: - composer-n1-webserver-2, composer-n1-webserver-4 - or composer-n1-webserver-8. Supported for Cloud - Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.maintenanceWindow`` - - - Maintenance window during which Cloud Composer - components may be under maintenance. - - - ``config.workloadsConfig`` - - - The workloads configuration settings for the GKE - cluster associated with the Cloud Composer - environment. Supported for Cloud Composer - environments in versions - composer-2.\ *.*-airflow-*.*.\* and newer. - - - ``config.environmentSize`` - - - The size of the Cloud Composer environment. - Supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and - newer. - - 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.orchestration.airflow.service_v1beta1.types.Environment` - An environment for running orchestration tasks. - - """ - # 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. - flattened_params = [name, environment, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateEnvironmentRequest): - request = environments.UpdateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if environment is not None: - request.environment = environment - 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_environment] - - # 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, - environments.Environment, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_environment(self, - request: Optional[Union[environments.DeleteEnvironmentRequest, 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"""Delete an environment. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_delete_environment(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteEnvironmentRequest( - ) - - # Make the request - operation = client.delete_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteEnvironmentRequest, dict]): - The request object. Delete an environment. - name (str): - The environment to delete, in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteEnvironmentRequest): - request = environments.DeleteEnvironmentRequest(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_environment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def restart_web_server(self, - request: Optional[Union[environments.RestartWebServerRequest, dict]] = 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"""Restart Airflow web server. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_restart_web_server(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.RestartWebServerRequest( - ) - - # Make the request - operation = client.restart_web_server(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest, dict]): - The request object. Restart Airflow web server. - retry (google.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.orchestration.airflow.service_v1beta1.types.Environment` - An environment for running orchestration tasks. - - """ - # 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, environments.RestartWebServerRequest): - request = environments.RestartWebServerRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.restart_web_server] - - # 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, - environments.Environment, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def check_upgrade(self, - request: Optional[Union[environments.CheckUpgradeRequest, dict]] = 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"""Check if an upgrade operation on the environment will - succeed. - In case of problems detailed info can be found in the - returned 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.orchestration.airflow import service_v1beta1 - - def sample_check_upgrade(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.CheckUpgradeRequest( - ) - - # Make the request - operation = client.check_upgrade(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeRequest, dict]): - The request object. Request to check whether image - upgrade will succeed. - retry (google.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.orchestration.airflow.service_v1beta1.types.CheckUpgradeResponse` Message containing information about the result of an upgrade check - operation. - - """ - # 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, environments.CheckUpgradeRequest): - request = environments.CheckUpgradeRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.check_upgrade] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.CheckUpgradeResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def execute_airflow_command(self, - request: Optional[Union[environments.ExecuteAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.ExecuteAirflowCommandResponse: - r"""Executes Airflow CLI command. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_execute_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.ExecuteAirflowCommandRequest( - ) - - # Make the request - response = client.execute_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandRequest, dict]): - The request object. Execute Airflow Command request. - retry (google.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.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandResponse: - Response to - ExecuteAirflowCommandRequest. - - """ - # 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, environments.ExecuteAirflowCommandRequest): - request = environments.ExecuteAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.execute_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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 stop_airflow_command(self, - request: Optional[Union[environments.StopAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.StopAirflowCommandResponse: - r"""Stops Airflow CLI command execution. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_stop_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.StopAirflowCommandRequest( - ) - - # Make the request - response = client.stop_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest, dict]): - The request object. Stop Airflow Command request. - retry (google.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.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse: - Response to - StopAirflowCommandRequest. - - """ - # 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, environments.StopAirflowCommandRequest): - request = environments.StopAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.stop_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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 poll_airflow_command(self, - request: Optional[Union[environments.PollAirflowCommandRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.PollAirflowCommandResponse: - r"""Polls Airflow CLI command execution and fetches logs. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_poll_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.PollAirflowCommandRequest( - ) - - # Make the request - response = client.poll_airflow_command(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest, dict]): - The request object. Poll Airflow Command request. - retry (google.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.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse: - Response to - PollAirflowCommandRequest. - - """ - # 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, environments.PollAirflowCommandRequest): - request = environments.PollAirflowCommandRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.poll_airflow_command] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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_workloads(self, - request: Optional[Union[environments.ListWorkloadsRequest, 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.ListWorkloadsPager: - r"""Lists workloads in a Cloud Composer environment. Workload is a - unit that runs a single Composer component. - - This method is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_list_workloads(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.ListWorkloadsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workloads(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest, dict]): - The request object. Request for listing workloads in a - Cloud Composer environment. - parent (str): - Required. The environment name to get - workloads for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListWorkloadsPager: - Response to ListWorkloadsRequest. - - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListWorkloadsRequest): - request = environments.ListWorkloadsRequest(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_workloads] - - # 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.ListWorkloadsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_user_workloads_secret(self, - request: Optional[Union[environments.CreateUserWorkloadsSecretRequest, dict]] = None, - *, - parent: Optional[str] = None, - user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_create_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateUserWorkloadsSecretRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsSecretRequest, dict]): - The request object. Create user workloads Secret request. - parent (str): - Required. The environment name to - create a Secret for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_workloads_secret (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret): - Required. User workloads Secret to - create. - - This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [parent, user_workloads_secret] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateUserWorkloadsSecretRequest): - request = environments.CreateUserWorkloadsSecretRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_workloads_secret is not None: - request.user_workloads_secret = user_workloads_secret - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_user_workloads_secret] - - # 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 get_user_workloads_secret(self, - request: Optional[Union[environments.GetUserWorkloadsSecretRequest, 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]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Gets an existing user workloads Secret. Values of the "data" - field in the response are cleared. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_get_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.GetUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - response = client.get_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsSecretRequest, dict]): - The request object. Get user workloads Secret request. - name (str): - Required. The resource name of the - Secret to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" - - 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetUserWorkloadsSecretRequest): - request = environments.GetUserWorkloadsSecretRequest(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_user_workloads_secret] - - # 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_user_workloads_secrets(self, - request: Optional[Union[environments.ListUserWorkloadsSecretsRequest, 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.ListUserWorkloadsSecretsPager: - r"""Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_list_user_workloads_secrets(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.ListUserWorkloadsSecretsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_secrets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest, dict]): - The request object. List user workloads Secrets request. - parent (str): - Required. List Secrets in the given - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsSecretsPager: - The user workloads Secrets for a - given environment. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListUserWorkloadsSecretsRequest): - request = environments.ListUserWorkloadsSecretsRequest(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_user_workloads_secrets] - - # 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.ListUserWorkloadsSecretsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_user_workloads_secret(self, - request: Optional[Union[environments.UpdateUserWorkloadsSecretRequest, dict]] = None, - *, - user_workloads_secret: Optional[environments.UserWorkloadsSecret] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_update_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateUserWorkloadsSecretRequest( - ) - - # Make the request - response = client.update_user_workloads_secret(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsSecretRequest, dict]): - The request object. Update user workloads Secret request. - user_workloads_secret (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret): - Optional. User workloads Secret to - override. - - This corresponds to the ``user_workloads_secret`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - # 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. - flattened_params = [user_workloads_secret] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateUserWorkloadsSecretRequest): - request = environments.UpdateUserWorkloadsSecretRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if user_workloads_secret is not None: - request.user_workloads_secret = user_workloads_secret - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_user_workloads_secret] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user_workloads_secret.name", request.user_workloads_secret.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_user_workloads_secret(self, - request: Optional[Union[environments.DeleteUserWorkloadsSecretRequest, 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]]] = (), - ) -> None: - r"""Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_delete_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - client.delete_user_workloads_secret(request=request) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsSecretRequest, dict]): - The request object. Delete user workloads Secret request. - name (str): - Required. The Secret to delete, in - the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}" - - 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`. - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteUserWorkloadsSecretRequest): - request = environments.DeleteUserWorkloadsSecretRequest(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_user_workloads_secret] - - # 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 create_user_workloads_config_map(self, - request: Optional[Union[environments.CreateUserWorkloadsConfigMapRequest, dict]] = None, - *, - parent: Optional[str] = None, - user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_create_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateUserWorkloadsConfigMapRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsConfigMapRequest, dict]): - The request object. Create user workloads ConfigMap - request. - parent (str): - Required. The environment name to - create a ConfigMap for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user_workloads_config_map (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap): - Required. User workloads ConfigMap to - create. - - This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [parent, user_workloads_config_map] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.CreateUserWorkloadsConfigMapRequest): - request = environments.CreateUserWorkloadsConfigMapRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user_workloads_config_map is not None: - request.user_workloads_config_map = user_workloads_config_map - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_user_workloads_config_map] - - # 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 get_user_workloads_config_map(self, - request: Optional[Union[environments.GetUserWorkloadsConfigMapRequest, 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]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_get_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.GetUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - response = client.get_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsConfigMapRequest, dict]): - The request object. Get user workloads ConfigMap request. - name (str): - Required. The resource name of the - ConfigMap to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" - - 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.GetUserWorkloadsConfigMapRequest): - request = environments.GetUserWorkloadsConfigMapRequest(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_user_workloads_config_map] - - # 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_user_workloads_config_maps(self, - request: Optional[Union[environments.ListUserWorkloadsConfigMapsRequest, 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.ListUserWorkloadsConfigMapsPager: - r"""Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_list_user_workloads_config_maps(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.ListUserWorkloadsConfigMapsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_config_maps(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest, dict]): - The request object. List user workloads ConfigMaps - request. - parent (str): - Required. List ConfigMaps in the - given environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - 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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsConfigMapsPager: - The user workloads ConfigMaps for a - given environment. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.ListUserWorkloadsConfigMapsRequest): - request = environments.ListUserWorkloadsConfigMapsRequest(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_user_workloads_config_maps] - - # 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.ListUserWorkloadsConfigMapsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_user_workloads_config_map(self, - request: Optional[Union[environments.UpdateUserWorkloadsConfigMapRequest, dict]] = None, - *, - user_workloads_config_map: Optional[environments.UserWorkloadsConfigMap] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_update_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateUserWorkloadsConfigMapRequest( - ) - - # Make the request - response = client.update_user_workloads_config_map(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsConfigMapRequest, dict]): - The request object. Update user workloads ConfigMap - request. - user_workloads_config_map (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap): - Optional. User workloads ConfigMap to - override. - - This corresponds to the ``user_workloads_config_map`` 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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - # 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. - flattened_params = [user_workloads_config_map] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.UpdateUserWorkloadsConfigMapRequest): - request = environments.UpdateUserWorkloadsConfigMapRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if user_workloads_config_map is not None: - request.user_workloads_config_map = user_workloads_config_map - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_user_workloads_config_map] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user_workloads_config_map.name", request.user_workloads_config_map.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_user_workloads_config_map(self, - request: Optional[Union[environments.DeleteUserWorkloadsConfigMapRequest, 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]]] = (), - ) -> None: - r"""Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_delete_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - client.delete_user_workloads_config_map(request=request) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsConfigMapRequest, dict]): - The request object. Delete user workloads ConfigMap - request. - name (str): - Required. The ConfigMap to delete, in - the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}" - - 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`. - """ - # 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. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, environments.DeleteUserWorkloadsConfigMapRequest): - request = environments.DeleteUserWorkloadsConfigMapRequest(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_user_workloads_config_map] - - # 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 save_snapshot(self, - request: Optional[Union[environments.SaveSnapshotRequest, dict]] = 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 snapshots of a Cloud Composer environment. - - As a result of this operation, snapshot of environment's - state is stored in a location specified in the - SaveSnapshotRequest. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_save_snapshot(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.SaveSnapshotRequest( - ) - - # Make the request - operation = client.save_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest, dict]): - The request object. Request to create a snapshot of a - Cloud Composer environment. - retry (google.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.orchestration.airflow.service_v1beta1.types.SaveSnapshotResponse` - Response to SaveSnapshotRequest. - - """ - # 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, environments.SaveSnapshotRequest): - request = environments.SaveSnapshotRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.save_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.SaveSnapshotResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def load_snapshot(self, - request: Optional[Union[environments.LoadSnapshotRequest, dict]] = 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"""Loads a snapshot of a Cloud Composer environment. - - As a result of this operation, a snapshot of - environment's specified in LoadSnapshotRequest is loaded - into the environment. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_load_snapshot(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.LoadSnapshotRequest( - ) - - # Make the request - operation = client.load_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest, dict]): - The request object. Request to load a snapshot into a - Cloud Composer environment. - retry (google.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.orchestration.airflow.service_v1beta1.types.LoadSnapshotResponse` - Response to LoadSnapshotRequest. - - """ - # 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, environments.LoadSnapshotRequest): - request = environments.LoadSnapshotRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.load_snapshot] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.LoadSnapshotResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def database_failover(self, - request: Optional[Union[environments.DatabaseFailoverRequest, dict]] = 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"""Triggers database failover (only for highly resilient - environments). - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_database_failover(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.DatabaseFailoverRequest( - ) - - # Make the request - operation = client.database_failover(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseFailoverRequest, dict]): - The request object. Request to trigger database failover - (only for highly resilient - environments). - retry (google.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.orchestration.airflow.service_v1beta1.types.DatabaseFailoverResponse` - Response for DatabaseFailoverRequest. - - """ - # 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, environments.DatabaseFailoverRequest): - request = environments.DatabaseFailoverRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.database_failover] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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, - environments.DatabaseFailoverResponse, - metadata_type=operations.OperationMetadata, - ) - - # Done; return the response. - return response - - def fetch_database_properties(self, - request: Optional[Union[environments.FetchDatabasePropertiesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> environments.FetchDatabasePropertiesResponse: - r"""Fetches database properties. - - .. 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.orchestration.airflow import service_v1beta1 - - def sample_fetch_database_properties(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.FetchDatabasePropertiesRequest( - environment="environment_value", - ) - - # Make the request - response = client.fetch_database_properties(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesRequest, dict]): - The request object. Request to fetch properties of - environment's database. - retry (google.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.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesResponse: - Response for - FetchDatabasePropertiesRequest. - - """ - # 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, environments.FetchDatabasePropertiesRequest): - request = environments.FetchDatabasePropertiesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.fetch_database_properties] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("environment", request.environment), - )), - ) - - # 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) -> "EnvironmentsClient": - 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() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - 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() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - 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,) - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EnvironmentsClient", -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py deleted file mode 100644 index 3def185aed80..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py +++ /dev/null @@ -1,583 +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.orchestration.airflow.service_v1beta1.types import environments - - -class ListEnvironmentsPager: - """A pager for iterating through ``list_environments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEnvironments`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse` - 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[..., environments.ListEnvironmentsResponse], - request: environments.ListEnvironmentsRequest, - response: environments.ListEnvironmentsResponse, - *, - 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.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse): - 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 = environments.ListEnvironmentsRequest(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[environments.ListEnvironmentsResponse]: - 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[environments.Environment]: - for page in self.pages: - yield from page.environments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEnvironmentsAsyncPager: - """A pager for iterating through ``list_environments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``environments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEnvironments`` requests and continue to iterate - through the ``environments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse` - 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[environments.ListEnvironmentsResponse]], - request: environments.ListEnvironmentsRequest, - response: environments.ListEnvironmentsResponse, - *, - 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.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse): - 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 = environments.ListEnvironmentsRequest(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[environments.ListEnvironmentsResponse]: - 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[environments.Environment]: - async def async_generator(): - async for page in self.pages: - for response in page.environments: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkloadsPager: - """A pager for iterating through ``list_workloads`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``workloads`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListWorkloads`` requests and continue to iterate - through the ``workloads`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse` - 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[..., environments.ListWorkloadsResponse], - request: environments.ListWorkloadsRequest, - response: environments.ListWorkloadsResponse, - *, - 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.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse): - 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 = environments.ListWorkloadsRequest(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[environments.ListWorkloadsResponse]: - 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[environments.ListWorkloadsResponse.ComposerWorkload]: - for page in self.pages: - yield from page.workloads - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListWorkloadsAsyncPager: - """A pager for iterating through ``list_workloads`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``workloads`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListWorkloads`` requests and continue to iterate - through the ``workloads`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse` - 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[environments.ListWorkloadsResponse]], - request: environments.ListWorkloadsRequest, - response: environments.ListWorkloadsResponse, - *, - 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.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse): - 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 = environments.ListWorkloadsRequest(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[environments.ListWorkloadsResponse]: - 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[environments.ListWorkloadsResponse.ComposerWorkload]: - async def async_generator(): - async for page in self.pages: - for response in page.workloads: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUserWorkloadsSecretsPager: - """A pager for iterating through ``list_user_workloads_secrets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``user_workloads_secrets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUserWorkloadsSecrets`` requests and continue to iterate - through the ``user_workloads_secrets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse` - 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[..., environments.ListUserWorkloadsSecretsResponse], - request: environments.ListUserWorkloadsSecretsRequest, - response: environments.ListUserWorkloadsSecretsResponse, - *, - 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.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse): - 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 = environments.ListUserWorkloadsSecretsRequest(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[environments.ListUserWorkloadsSecretsResponse]: - 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[environments.UserWorkloadsSecret]: - for page in self.pages: - yield from page.user_workloads_secrets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUserWorkloadsSecretsAsyncPager: - """A pager for iterating through ``list_user_workloads_secrets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``user_workloads_secrets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUserWorkloadsSecrets`` requests and continue to iterate - through the ``user_workloads_secrets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse` - 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[environments.ListUserWorkloadsSecretsResponse]], - request: environments.ListUserWorkloadsSecretsRequest, - response: environments.ListUserWorkloadsSecretsResponse, - *, - 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.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse): - 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 = environments.ListUserWorkloadsSecretsRequest(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[environments.ListUserWorkloadsSecretsResponse]: - 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[environments.UserWorkloadsSecret]: - async def async_generator(): - async for page in self.pages: - for response in page.user_workloads_secrets: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUserWorkloadsConfigMapsPager: - """A pager for iterating through ``list_user_workloads_config_maps`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``user_workloads_config_maps`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUserWorkloadsConfigMaps`` requests and continue to iterate - through the ``user_workloads_config_maps`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse` - 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[..., environments.ListUserWorkloadsConfigMapsResponse], - request: environments.ListUserWorkloadsConfigMapsRequest, - response: environments.ListUserWorkloadsConfigMapsResponse, - *, - 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.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse): - 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 = environments.ListUserWorkloadsConfigMapsRequest(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[environments.ListUserWorkloadsConfigMapsResponse]: - 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[environments.UserWorkloadsConfigMap]: - for page in self.pages: - yield from page.user_workloads_config_maps - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUserWorkloadsConfigMapsAsyncPager: - """A pager for iterating through ``list_user_workloads_config_maps`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``user_workloads_config_maps`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUserWorkloadsConfigMaps`` requests and continue to iterate - through the ``user_workloads_config_maps`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse` - 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[environments.ListUserWorkloadsConfigMapsResponse]], - request: environments.ListUserWorkloadsConfigMapsRequest, - response: environments.ListUserWorkloadsConfigMapsResponse, - *, - 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.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse): - 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 = environments.ListUserWorkloadsConfigMapsRequest(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[environments.ListUserWorkloadsConfigMapsResponse]: - 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[environments.UserWorkloadsConfigMap]: - async def async_generator(): - async for page in self.pages: - for response in page.user_workloads_config_maps: - 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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/README.rst deleted file mode 100644 index bce85d4987a6..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`EnvironmentsTransport` is the ABC for all transports. -- public child `EnvironmentsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `EnvironmentsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseEnvironmentsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `EnvironmentsRestTransport` 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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/__init__.py deleted file mode 100644 index 0fb4434d4920..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/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 EnvironmentsTransport -from .grpc import EnvironmentsGrpcTransport -from .grpc_asyncio import EnvironmentsGrpcAsyncIOTransport -from .rest import EnvironmentsRestTransport -from .rest import EnvironmentsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EnvironmentsTransport]] -_transport_registry['grpc'] = EnvironmentsGrpcTransport -_transport_registry['grpc_asyncio'] = EnvironmentsGrpcAsyncIOTransport -_transport_registry['rest'] = EnvironmentsRestTransport - -__all__ = ( - 'EnvironmentsTransport', - 'EnvironmentsGrpcTransport', - 'EnvironmentsGrpcAsyncIOTransport', - 'EnvironmentsRestTransport', - 'EnvironmentsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py deleted file mode 100644 index a53951978f34..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py +++ /dev/null @@ -1,540 +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.orchestration.airflow.service_v1beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.orchestration.airflow.service_v1beta1.types import environments -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class EnvironmentsTransport(abc.ABC): - """Abstract transport class for Environments.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'composer.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: 'composer.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_environment: gapic_v1.method.wrap_method( - self.create_environment, - default_timeout=None, - client_info=client_info, - ), - self.get_environment: gapic_v1.method.wrap_method( - self.get_environment, - default_timeout=None, - client_info=client_info, - ), - self.list_environments: gapic_v1.method.wrap_method( - self.list_environments, - default_timeout=None, - client_info=client_info, - ), - self.update_environment: gapic_v1.method.wrap_method( - self.update_environment, - default_timeout=None, - client_info=client_info, - ), - self.delete_environment: gapic_v1.method.wrap_method( - self.delete_environment, - default_timeout=None, - client_info=client_info, - ), - self.restart_web_server: gapic_v1.method.wrap_method( - self.restart_web_server, - default_timeout=None, - client_info=client_info, - ), - self.check_upgrade: gapic_v1.method.wrap_method( - self.check_upgrade, - default_timeout=None, - client_info=client_info, - ), - self.execute_airflow_command: gapic_v1.method.wrap_method( - self.execute_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.stop_airflow_command: gapic_v1.method.wrap_method( - self.stop_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.poll_airflow_command: gapic_v1.method.wrap_method( - self.poll_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.list_workloads: gapic_v1.method.wrap_method( - self.list_workloads, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_secret: gapic_v1.method.wrap_method( - self.create_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_secret: gapic_v1.method.wrap_method( - self.get_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_secrets: gapic_v1.method.wrap_method( - self.list_user_workloads_secrets, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_secret: gapic_v1.method.wrap_method( - self.update_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_secret: gapic_v1.method.wrap_method( - self.delete_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_config_map: gapic_v1.method.wrap_method( - self.create_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_config_map: gapic_v1.method.wrap_method( - self.get_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_config_maps: gapic_v1.method.wrap_method( - self.list_user_workloads_config_maps, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_config_map: gapic_v1.method.wrap_method( - self.update_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_config_map: gapic_v1.method.wrap_method( - self.delete_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.save_snapshot: gapic_v1.method.wrap_method( - self.save_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.load_snapshot: gapic_v1.method.wrap_method( - self.load_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.database_failover: gapic_v1.method.wrap_method( - self.database_failover, - default_timeout=None, - client_info=client_info, - ), - self.fetch_database_properties: gapic_v1.method.wrap_method( - self.fetch_database_properties, - 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_environment(self) -> Callable[ - [environments.CreateEnvironmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_environment(self) -> Callable[ - [environments.GetEnvironmentRequest], - Union[ - environments.Environment, - Awaitable[environments.Environment] - ]]: - raise NotImplementedError() - - @property - def list_environments(self) -> Callable[ - [environments.ListEnvironmentsRequest], - Union[ - environments.ListEnvironmentsResponse, - Awaitable[environments.ListEnvironmentsResponse] - ]]: - raise NotImplementedError() - - @property - def update_environment(self) -> Callable[ - [environments.UpdateEnvironmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_environment(self) -> Callable[ - [environments.DeleteEnvironmentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def restart_web_server(self) -> Callable[ - [environments.RestartWebServerRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def check_upgrade(self) -> Callable[ - [environments.CheckUpgradeRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def execute_airflow_command(self) -> Callable[ - [environments.ExecuteAirflowCommandRequest], - Union[ - environments.ExecuteAirflowCommandResponse, - Awaitable[environments.ExecuteAirflowCommandResponse] - ]]: - raise NotImplementedError() - - @property - def stop_airflow_command(self) -> Callable[ - [environments.StopAirflowCommandRequest], - Union[ - environments.StopAirflowCommandResponse, - Awaitable[environments.StopAirflowCommandResponse] - ]]: - raise NotImplementedError() - - @property - def poll_airflow_command(self) -> Callable[ - [environments.PollAirflowCommandRequest], - Union[ - environments.PollAirflowCommandResponse, - Awaitable[environments.PollAirflowCommandResponse] - ]]: - raise NotImplementedError() - - @property - def list_workloads(self) -> Callable[ - [environments.ListWorkloadsRequest], - Union[ - environments.ListWorkloadsResponse, - Awaitable[environments.ListWorkloadsResponse] - ]]: - raise NotImplementedError() - - @property - def create_user_workloads_secret(self) -> Callable[ - [environments.CreateUserWorkloadsSecretRequest], - Union[ - environments.UserWorkloadsSecret, - Awaitable[environments.UserWorkloadsSecret] - ]]: - raise NotImplementedError() - - @property - def get_user_workloads_secret(self) -> Callable[ - [environments.GetUserWorkloadsSecretRequest], - Union[ - environments.UserWorkloadsSecret, - Awaitable[environments.UserWorkloadsSecret] - ]]: - raise NotImplementedError() - - @property - def list_user_workloads_secrets(self) -> Callable[ - [environments.ListUserWorkloadsSecretsRequest], - Union[ - environments.ListUserWorkloadsSecretsResponse, - Awaitable[environments.ListUserWorkloadsSecretsResponse] - ]]: - raise NotImplementedError() - - @property - def update_user_workloads_secret(self) -> Callable[ - [environments.UpdateUserWorkloadsSecretRequest], - Union[ - environments.UserWorkloadsSecret, - Awaitable[environments.UserWorkloadsSecret] - ]]: - raise NotImplementedError() - - @property - def delete_user_workloads_secret(self) -> Callable[ - [environments.DeleteUserWorkloadsSecretRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def create_user_workloads_config_map(self) -> Callable[ - [environments.CreateUserWorkloadsConfigMapRequest], - Union[ - environments.UserWorkloadsConfigMap, - Awaitable[environments.UserWorkloadsConfigMap] - ]]: - raise NotImplementedError() - - @property - def get_user_workloads_config_map(self) -> Callable[ - [environments.GetUserWorkloadsConfigMapRequest], - Union[ - environments.UserWorkloadsConfigMap, - Awaitable[environments.UserWorkloadsConfigMap] - ]]: - raise NotImplementedError() - - @property - def list_user_workloads_config_maps(self) -> Callable[ - [environments.ListUserWorkloadsConfigMapsRequest], - Union[ - environments.ListUserWorkloadsConfigMapsResponse, - Awaitable[environments.ListUserWorkloadsConfigMapsResponse] - ]]: - raise NotImplementedError() - - @property - def update_user_workloads_config_map(self) -> Callable[ - [environments.UpdateUserWorkloadsConfigMapRequest], - Union[ - environments.UserWorkloadsConfigMap, - Awaitable[environments.UserWorkloadsConfigMap] - ]]: - raise NotImplementedError() - - @property - def delete_user_workloads_config_map(self) -> Callable[ - [environments.DeleteUserWorkloadsConfigMapRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def save_snapshot(self) -> Callable[ - [environments.SaveSnapshotRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def load_snapshot(self) -> Callable[ - [environments.LoadSnapshotRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def database_failover(self) -> Callable[ - [environments.DatabaseFailoverRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def fetch_database_properties(self) -> Callable[ - [environments.FetchDatabasePropertiesRequest], - Union[ - environments.FetchDatabasePropertiesResponse, - Awaitable[environments.FetchDatabasePropertiesResponse] - ]]: - 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 delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'EnvironmentsTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py deleted file mode 100644 index 0c3924547dc3..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py +++ /dev/null @@ -1,1096 +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.orchestration.airflow.service_v1beta1.types import environments -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import EnvironmentsTransport, 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.orchestration.airflow.service.v1beta1.Environments", - "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.orchestration.airflow.service.v1beta1.Environments", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class EnvironmentsGrpcTransport(EnvironmentsTransport): - """gRPC backend transport for Environments. - - Managed Apache Airflow Environments. - - 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 = 'composer.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: 'composer.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 = 'composer.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_environment(self) -> Callable[ - [environments.CreateEnvironmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the create environment method over gRPC. - - Create a new environment. - - Returns: - Callable[[~.CreateEnvironmentRequest], - ~.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_environment' not in self._stubs: - self._stubs['create_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateEnvironment', - request_serializer=environments.CreateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_environment'] - - @property - def get_environment(self) -> Callable[ - [environments.GetEnvironmentRequest], - environments.Environment]: - r"""Return a callable for the get environment method over gRPC. - - Get an existing environment. - - Returns: - Callable[[~.GetEnvironmentRequest], - ~.Environment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_environment' not in self._stubs: - self._stubs['get_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetEnvironment', - request_serializer=environments.GetEnvironmentRequest.serialize, - response_deserializer=environments.Environment.deserialize, - ) - return self._stubs['get_environment'] - - @property - def list_environments(self) -> Callable[ - [environments.ListEnvironmentsRequest], - environments.ListEnvironmentsResponse]: - r"""Return a callable for the list environments method over gRPC. - - List environments. - - Returns: - Callable[[~.ListEnvironmentsRequest], - ~.ListEnvironmentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_environments' not in self._stubs: - self._stubs['list_environments'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListEnvironments', - request_serializer=environments.ListEnvironmentsRequest.serialize, - response_deserializer=environments.ListEnvironmentsResponse.deserialize, - ) - return self._stubs['list_environments'] - - @property - def update_environment(self) -> Callable[ - [environments.UpdateEnvironmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the update environment method over gRPC. - - Update an environment. - - Returns: - Callable[[~.UpdateEnvironmentRequest], - ~.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_environment' not in self._stubs: - self._stubs['update_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateEnvironment', - request_serializer=environments.UpdateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_environment'] - - @property - def delete_environment(self) -> Callable[ - [environments.DeleteEnvironmentRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete environment method over gRPC. - - Delete an environment. - - Returns: - Callable[[~.DeleteEnvironmentRequest], - ~.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_environment' not in self._stubs: - self._stubs['delete_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteEnvironment', - request_serializer=environments.DeleteEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_environment'] - - @property - def restart_web_server(self) -> Callable[ - [environments.RestartWebServerRequest], - operations_pb2.Operation]: - r"""Return a callable for the restart web server method over gRPC. - - Restart Airflow web server. - - Returns: - Callable[[~.RestartWebServerRequest], - ~.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 'restart_web_server' not in self._stubs: - self._stubs['restart_web_server'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/RestartWebServer', - request_serializer=environments.RestartWebServerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['restart_web_server'] - - @property - def check_upgrade(self) -> Callable[ - [environments.CheckUpgradeRequest], - operations_pb2.Operation]: - r"""Return a callable for the check upgrade method over gRPC. - - Check if an upgrade operation on the environment will - succeed. - In case of problems detailed info can be found in the - returned Operation. - - Returns: - Callable[[~.CheckUpgradeRequest], - ~.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 'check_upgrade' not in self._stubs: - self._stubs['check_upgrade'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CheckUpgrade', - request_serializer=environments.CheckUpgradeRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['check_upgrade'] - - @property - def execute_airflow_command(self) -> Callable[ - [environments.ExecuteAirflowCommandRequest], - environments.ExecuteAirflowCommandResponse]: - r"""Return a callable for the execute airflow command method over gRPC. - - Executes Airflow CLI command. - - Returns: - Callable[[~.ExecuteAirflowCommandRequest], - ~.ExecuteAirflowCommandResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'execute_airflow_command' not in self._stubs: - self._stubs['execute_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ExecuteAirflowCommand', - request_serializer=environments.ExecuteAirflowCommandRequest.serialize, - response_deserializer=environments.ExecuteAirflowCommandResponse.deserialize, - ) - return self._stubs['execute_airflow_command'] - - @property - def stop_airflow_command(self) -> Callable[ - [environments.StopAirflowCommandRequest], - environments.StopAirflowCommandResponse]: - r"""Return a callable for the stop airflow command method over gRPC. - - Stops Airflow CLI command execution. - - Returns: - Callable[[~.StopAirflowCommandRequest], - ~.StopAirflowCommandResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_airflow_command' not in self._stubs: - self._stubs['stop_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/StopAirflowCommand', - request_serializer=environments.StopAirflowCommandRequest.serialize, - response_deserializer=environments.StopAirflowCommandResponse.deserialize, - ) - return self._stubs['stop_airflow_command'] - - @property - def poll_airflow_command(self) -> Callable[ - [environments.PollAirflowCommandRequest], - environments.PollAirflowCommandResponse]: - r"""Return a callable for the poll airflow command method over gRPC. - - Polls Airflow CLI command execution and fetches logs. - - Returns: - Callable[[~.PollAirflowCommandRequest], - ~.PollAirflowCommandResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'poll_airflow_command' not in self._stubs: - self._stubs['poll_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/PollAirflowCommand', - request_serializer=environments.PollAirflowCommandRequest.serialize, - response_deserializer=environments.PollAirflowCommandResponse.deserialize, - ) - return self._stubs['poll_airflow_command'] - - @property - def list_workloads(self) -> Callable[ - [environments.ListWorkloadsRequest], - environments.ListWorkloadsResponse]: - r"""Return a callable for the list workloads method over gRPC. - - Lists workloads in a Cloud Composer environment. Workload is a - unit that runs a single Composer component. - - This method is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - - Returns: - Callable[[~.ListWorkloadsRequest], - ~.ListWorkloadsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workloads' not in self._stubs: - self._stubs['list_workloads'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListWorkloads', - request_serializer=environments.ListWorkloadsRequest.serialize, - response_deserializer=environments.ListWorkloadsResponse.deserialize, - ) - return self._stubs['list_workloads'] - - @property - def create_user_workloads_secret(self) -> Callable[ - [environments.CreateUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - r"""Return a callable for the create user workloads secret method over gRPC. - - Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.CreateUserWorkloadsSecretRequest], - ~.UserWorkloadsSecret]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['create_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateUserWorkloadsSecret', - request_serializer=environments.CreateUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['create_user_workloads_secret'] - - @property - def get_user_workloads_secret(self) -> Callable[ - [environments.GetUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - r"""Return a callable for the get user workloads secret method over gRPC. - - Gets an existing user workloads Secret. Values of the "data" - field in the response are cleared. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.GetUserWorkloadsSecretRequest], - ~.UserWorkloadsSecret]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['get_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetUserWorkloadsSecret', - request_serializer=environments.GetUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['get_user_workloads_secret'] - - @property - def list_user_workloads_secrets(self) -> Callable[ - [environments.ListUserWorkloadsSecretsRequest], - environments.ListUserWorkloadsSecretsResponse]: - r"""Return a callable for the list user workloads secrets method over gRPC. - - Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.ListUserWorkloadsSecretsRequest], - ~.ListUserWorkloadsSecretsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secrets' not in self._stubs: - self._stubs['list_user_workloads_secrets'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListUserWorkloadsSecrets', - request_serializer=environments.ListUserWorkloadsSecretsRequest.serialize, - response_deserializer=environments.ListUserWorkloadsSecretsResponse.deserialize, - ) - return self._stubs['list_user_workloads_secrets'] - - @property - def update_user_workloads_secret(self) -> Callable[ - [environments.UpdateUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - r"""Return a callable for the update user workloads secret method over gRPC. - - Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.UpdateUserWorkloadsSecretRequest], - ~.UserWorkloadsSecret]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['update_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateUserWorkloadsSecret', - request_serializer=environments.UpdateUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['update_user_workloads_secret'] - - @property - def delete_user_workloads_secret(self) -> Callable[ - [environments.DeleteUserWorkloadsSecretRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete user workloads secret method over gRPC. - - Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.DeleteUserWorkloadsSecretRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['delete_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteUserWorkloadsSecret', - request_serializer=environments.DeleteUserWorkloadsSecretRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user_workloads_secret'] - - @property - def create_user_workloads_config_map(self) -> Callable[ - [environments.CreateUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - r"""Return a callable for the create user workloads config - map method over gRPC. - - Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.CreateUserWorkloadsConfigMapRequest], - ~.UserWorkloadsConfigMap]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['create_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateUserWorkloadsConfigMap', - request_serializer=environments.CreateUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['create_user_workloads_config_map'] - - @property - def get_user_workloads_config_map(self) -> Callable[ - [environments.GetUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - r"""Return a callable for the get user workloads config map method over gRPC. - - Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.GetUserWorkloadsConfigMapRequest], - ~.UserWorkloadsConfigMap]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['get_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetUserWorkloadsConfigMap', - request_serializer=environments.GetUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['get_user_workloads_config_map'] - - @property - def list_user_workloads_config_maps(self) -> Callable[ - [environments.ListUserWorkloadsConfigMapsRequest], - environments.ListUserWorkloadsConfigMapsResponse]: - r"""Return a callable for the list user workloads config - maps method over gRPC. - - Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.ListUserWorkloadsConfigMapsRequest], - ~.ListUserWorkloadsConfigMapsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_maps' not in self._stubs: - self._stubs['list_user_workloads_config_maps'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListUserWorkloadsConfigMaps', - request_serializer=environments.ListUserWorkloadsConfigMapsRequest.serialize, - response_deserializer=environments.ListUserWorkloadsConfigMapsResponse.deserialize, - ) - return self._stubs['list_user_workloads_config_maps'] - - @property - def update_user_workloads_config_map(self) -> Callable[ - [environments.UpdateUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - r"""Return a callable for the update user workloads config - map method over gRPC. - - Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.UpdateUserWorkloadsConfigMapRequest], - ~.UserWorkloadsConfigMap]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['update_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateUserWorkloadsConfigMap', - request_serializer=environments.UpdateUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['update_user_workloads_config_map'] - - @property - def delete_user_workloads_config_map(self) -> Callable[ - [environments.DeleteUserWorkloadsConfigMapRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete user workloads config - map method over gRPC. - - Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.DeleteUserWorkloadsConfigMapRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['delete_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteUserWorkloadsConfigMap', - request_serializer=environments.DeleteUserWorkloadsConfigMapRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user_workloads_config_map'] - - @property - def save_snapshot(self) -> Callable[ - [environments.SaveSnapshotRequest], - operations_pb2.Operation]: - r"""Return a callable for the save snapshot method over gRPC. - - Creates a snapshots of a Cloud Composer environment. - - As a result of this operation, snapshot of environment's - state is stored in a location specified in the - SaveSnapshotRequest. - - Returns: - Callable[[~.SaveSnapshotRequest], - ~.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 'save_snapshot' not in self._stubs: - self._stubs['save_snapshot'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/SaveSnapshot', - request_serializer=environments.SaveSnapshotRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['save_snapshot'] - - @property - def load_snapshot(self) -> Callable[ - [environments.LoadSnapshotRequest], - operations_pb2.Operation]: - r"""Return a callable for the load snapshot method over gRPC. - - Loads a snapshot of a Cloud Composer environment. - - As a result of this operation, a snapshot of - environment's specified in LoadSnapshotRequest is loaded - into the environment. - - Returns: - Callable[[~.LoadSnapshotRequest], - ~.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 'load_snapshot' not in self._stubs: - self._stubs['load_snapshot'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/LoadSnapshot', - request_serializer=environments.LoadSnapshotRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['load_snapshot'] - - @property - def database_failover(self) -> Callable[ - [environments.DatabaseFailoverRequest], - operations_pb2.Operation]: - r"""Return a callable for the database failover method over gRPC. - - Triggers database failover (only for highly resilient - environments). - - Returns: - Callable[[~.DatabaseFailoverRequest], - ~.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 'database_failover' not in self._stubs: - self._stubs['database_failover'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DatabaseFailover', - request_serializer=environments.DatabaseFailoverRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['database_failover'] - - @property - def fetch_database_properties(self) -> Callable[ - [environments.FetchDatabasePropertiesRequest], - environments.FetchDatabasePropertiesResponse]: - r"""Return a callable for the fetch database properties method over gRPC. - - Fetches database properties. - - Returns: - Callable[[~.FetchDatabasePropertiesRequest], - ~.FetchDatabasePropertiesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fetch_database_properties' not in self._stubs: - self._stubs['fetch_database_properties'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/FetchDatabaseProperties', - request_serializer=environments.FetchDatabasePropertiesRequest.serialize, - response_deserializer=environments.FetchDatabasePropertiesResponse.deserialize, - ) - return self._stubs['fetch_database_properties'] - - 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 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__ = ( - 'EnvironmentsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py deleted file mode 100644 index 02072338d533..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py +++ /dev/null @@ -1,1251 +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.orchestration.airflow.service_v1beta1.types import environments -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO -from .grpc import EnvironmentsGrpcTransport - -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.orchestration.airflow.service.v1beta1.Environments", - "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.orchestration.airflow.service.v1beta1.Environments", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): - """gRPC AsyncIO backend transport for Environments. - - Managed Apache Airflow Environments. - - 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 = 'composer.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 = 'composer.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: 'composer.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_environment(self) -> Callable[ - [environments.CreateEnvironmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create environment method over gRPC. - - Create a new environment. - - Returns: - Callable[[~.CreateEnvironmentRequest], - 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_environment' not in self._stubs: - self._stubs['create_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateEnvironment', - request_serializer=environments.CreateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_environment'] - - @property - def get_environment(self) -> Callable[ - [environments.GetEnvironmentRequest], - Awaitable[environments.Environment]]: - r"""Return a callable for the get environment method over gRPC. - - Get an existing environment. - - Returns: - Callable[[~.GetEnvironmentRequest], - Awaitable[~.Environment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_environment' not in self._stubs: - self._stubs['get_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetEnvironment', - request_serializer=environments.GetEnvironmentRequest.serialize, - response_deserializer=environments.Environment.deserialize, - ) - return self._stubs['get_environment'] - - @property - def list_environments(self) -> Callable[ - [environments.ListEnvironmentsRequest], - Awaitable[environments.ListEnvironmentsResponse]]: - r"""Return a callable for the list environments method over gRPC. - - List environments. - - Returns: - Callable[[~.ListEnvironmentsRequest], - Awaitable[~.ListEnvironmentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_environments' not in self._stubs: - self._stubs['list_environments'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListEnvironments', - request_serializer=environments.ListEnvironmentsRequest.serialize, - response_deserializer=environments.ListEnvironmentsResponse.deserialize, - ) - return self._stubs['list_environments'] - - @property - def update_environment(self) -> Callable[ - [environments.UpdateEnvironmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update environment method over gRPC. - - Update an environment. - - Returns: - Callable[[~.UpdateEnvironmentRequest], - 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_environment' not in self._stubs: - self._stubs['update_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateEnvironment', - request_serializer=environments.UpdateEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_environment'] - - @property - def delete_environment(self) -> Callable[ - [environments.DeleteEnvironmentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete environment method over gRPC. - - Delete an environment. - - Returns: - Callable[[~.DeleteEnvironmentRequest], - 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_environment' not in self._stubs: - self._stubs['delete_environment'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteEnvironment', - request_serializer=environments.DeleteEnvironmentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_environment'] - - @property - def restart_web_server(self) -> Callable[ - [environments.RestartWebServerRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the restart web server method over gRPC. - - Restart Airflow web server. - - Returns: - Callable[[~.RestartWebServerRequest], - 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 'restart_web_server' not in self._stubs: - self._stubs['restart_web_server'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/RestartWebServer', - request_serializer=environments.RestartWebServerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['restart_web_server'] - - @property - def check_upgrade(self) -> Callable[ - [environments.CheckUpgradeRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the check upgrade method over gRPC. - - Check if an upgrade operation on the environment will - succeed. - In case of problems detailed info can be found in the - returned Operation. - - Returns: - Callable[[~.CheckUpgradeRequest], - 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 'check_upgrade' not in self._stubs: - self._stubs['check_upgrade'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CheckUpgrade', - request_serializer=environments.CheckUpgradeRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['check_upgrade'] - - @property - def execute_airflow_command(self) -> Callable[ - [environments.ExecuteAirflowCommandRequest], - Awaitable[environments.ExecuteAirflowCommandResponse]]: - r"""Return a callable for the execute airflow command method over gRPC. - - Executes Airflow CLI command. - - Returns: - Callable[[~.ExecuteAirflowCommandRequest], - Awaitable[~.ExecuteAirflowCommandResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'execute_airflow_command' not in self._stubs: - self._stubs['execute_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ExecuteAirflowCommand', - request_serializer=environments.ExecuteAirflowCommandRequest.serialize, - response_deserializer=environments.ExecuteAirflowCommandResponse.deserialize, - ) - return self._stubs['execute_airflow_command'] - - @property - def stop_airflow_command(self) -> Callable[ - [environments.StopAirflowCommandRequest], - Awaitable[environments.StopAirflowCommandResponse]]: - r"""Return a callable for the stop airflow command method over gRPC. - - Stops Airflow CLI command execution. - - Returns: - Callable[[~.StopAirflowCommandRequest], - Awaitable[~.StopAirflowCommandResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'stop_airflow_command' not in self._stubs: - self._stubs['stop_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/StopAirflowCommand', - request_serializer=environments.StopAirflowCommandRequest.serialize, - response_deserializer=environments.StopAirflowCommandResponse.deserialize, - ) - return self._stubs['stop_airflow_command'] - - @property - def poll_airflow_command(self) -> Callable[ - [environments.PollAirflowCommandRequest], - Awaitable[environments.PollAirflowCommandResponse]]: - r"""Return a callable for the poll airflow command method over gRPC. - - Polls Airflow CLI command execution and fetches logs. - - Returns: - Callable[[~.PollAirflowCommandRequest], - Awaitable[~.PollAirflowCommandResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'poll_airflow_command' not in self._stubs: - self._stubs['poll_airflow_command'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/PollAirflowCommand', - request_serializer=environments.PollAirflowCommandRequest.serialize, - response_deserializer=environments.PollAirflowCommandResponse.deserialize, - ) - return self._stubs['poll_airflow_command'] - - @property - def list_workloads(self) -> Callable[ - [environments.ListWorkloadsRequest], - Awaitable[environments.ListWorkloadsResponse]]: - r"""Return a callable for the list workloads method over gRPC. - - Lists workloads in a Cloud Composer environment. Workload is a - unit that runs a single Composer component. - - This method is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - - Returns: - Callable[[~.ListWorkloadsRequest], - Awaitable[~.ListWorkloadsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_workloads' not in self._stubs: - self._stubs['list_workloads'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListWorkloads', - request_serializer=environments.ListWorkloadsRequest.serialize, - response_deserializer=environments.ListWorkloadsResponse.deserialize, - ) - return self._stubs['list_workloads'] - - @property - def create_user_workloads_secret(self) -> Callable[ - [environments.CreateUserWorkloadsSecretRequest], - Awaitable[environments.UserWorkloadsSecret]]: - r"""Return a callable for the create user workloads secret method over gRPC. - - Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.CreateUserWorkloadsSecretRequest], - Awaitable[~.UserWorkloadsSecret]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['create_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateUserWorkloadsSecret', - request_serializer=environments.CreateUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['create_user_workloads_secret'] - - @property - def get_user_workloads_secret(self) -> Callable[ - [environments.GetUserWorkloadsSecretRequest], - Awaitable[environments.UserWorkloadsSecret]]: - r"""Return a callable for the get user workloads secret method over gRPC. - - Gets an existing user workloads Secret. Values of the "data" - field in the response are cleared. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.GetUserWorkloadsSecretRequest], - Awaitable[~.UserWorkloadsSecret]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['get_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetUserWorkloadsSecret', - request_serializer=environments.GetUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['get_user_workloads_secret'] - - @property - def list_user_workloads_secrets(self) -> Callable[ - [environments.ListUserWorkloadsSecretsRequest], - Awaitable[environments.ListUserWorkloadsSecretsResponse]]: - r"""Return a callable for the list user workloads secrets method over gRPC. - - Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.ListUserWorkloadsSecretsRequest], - Awaitable[~.ListUserWorkloadsSecretsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secrets' not in self._stubs: - self._stubs['list_user_workloads_secrets'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListUserWorkloadsSecrets', - request_serializer=environments.ListUserWorkloadsSecretsRequest.serialize, - response_deserializer=environments.ListUserWorkloadsSecretsResponse.deserialize, - ) - return self._stubs['list_user_workloads_secrets'] - - @property - def update_user_workloads_secret(self) -> Callable[ - [environments.UpdateUserWorkloadsSecretRequest], - Awaitable[environments.UserWorkloadsSecret]]: - r"""Return a callable for the update user workloads secret method over gRPC. - - Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.UpdateUserWorkloadsSecretRequest], - Awaitable[~.UserWorkloadsSecret]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['update_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateUserWorkloadsSecret', - request_serializer=environments.UpdateUserWorkloadsSecretRequest.serialize, - response_deserializer=environments.UserWorkloadsSecret.deserialize, - ) - return self._stubs['update_user_workloads_secret'] - - @property - def delete_user_workloads_secret(self) -> Callable[ - [environments.DeleteUserWorkloadsSecretRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete user workloads secret method over gRPC. - - Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.DeleteUserWorkloadsSecretRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_secret' not in self._stubs: - self._stubs['delete_user_workloads_secret'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteUserWorkloadsSecret', - request_serializer=environments.DeleteUserWorkloadsSecretRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user_workloads_secret'] - - @property - def create_user_workloads_config_map(self) -> Callable[ - [environments.CreateUserWorkloadsConfigMapRequest], - Awaitable[environments.UserWorkloadsConfigMap]]: - r"""Return a callable for the create user workloads config - map method over gRPC. - - Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.CreateUserWorkloadsConfigMapRequest], - Awaitable[~.UserWorkloadsConfigMap]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['create_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/CreateUserWorkloadsConfigMap', - request_serializer=environments.CreateUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['create_user_workloads_config_map'] - - @property - def get_user_workloads_config_map(self) -> Callable[ - [environments.GetUserWorkloadsConfigMapRequest], - Awaitable[environments.UserWorkloadsConfigMap]]: - r"""Return a callable for the get user workloads config map method over gRPC. - - Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.GetUserWorkloadsConfigMapRequest], - Awaitable[~.UserWorkloadsConfigMap]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['get_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/GetUserWorkloadsConfigMap', - request_serializer=environments.GetUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['get_user_workloads_config_map'] - - @property - def list_user_workloads_config_maps(self) -> Callable[ - [environments.ListUserWorkloadsConfigMapsRequest], - Awaitable[environments.ListUserWorkloadsConfigMapsResponse]]: - r"""Return a callable for the list user workloads config - maps method over gRPC. - - Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.ListUserWorkloadsConfigMapsRequest], - Awaitable[~.ListUserWorkloadsConfigMapsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_maps' not in self._stubs: - self._stubs['list_user_workloads_config_maps'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/ListUserWorkloadsConfigMaps', - request_serializer=environments.ListUserWorkloadsConfigMapsRequest.serialize, - response_deserializer=environments.ListUserWorkloadsConfigMapsResponse.deserialize, - ) - return self._stubs['list_user_workloads_config_maps'] - - @property - def update_user_workloads_config_map(self) -> Callable[ - [environments.UpdateUserWorkloadsConfigMapRequest], - Awaitable[environments.UserWorkloadsConfigMap]]: - r"""Return a callable for the update user workloads config - map method over gRPC. - - Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.UpdateUserWorkloadsConfigMapRequest], - Awaitable[~.UserWorkloadsConfigMap]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['update_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/UpdateUserWorkloadsConfigMap', - request_serializer=environments.UpdateUserWorkloadsConfigMapRequest.serialize, - response_deserializer=environments.UserWorkloadsConfigMap.deserialize, - ) - return self._stubs['update_user_workloads_config_map'] - - @property - def delete_user_workloads_config_map(self) -> Callable[ - [environments.DeleteUserWorkloadsConfigMapRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete user workloads config - map method over gRPC. - - Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - - Returns: - Callable[[~.DeleteUserWorkloadsConfigMapRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_user_workloads_config_map' not in self._stubs: - self._stubs['delete_user_workloads_config_map'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DeleteUserWorkloadsConfigMap', - request_serializer=environments.DeleteUserWorkloadsConfigMapRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user_workloads_config_map'] - - @property - def save_snapshot(self) -> Callable[ - [environments.SaveSnapshotRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the save snapshot method over gRPC. - - Creates a snapshots of a Cloud Composer environment. - - As a result of this operation, snapshot of environment's - state is stored in a location specified in the - SaveSnapshotRequest. - - Returns: - Callable[[~.SaveSnapshotRequest], - 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 'save_snapshot' not in self._stubs: - self._stubs['save_snapshot'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/SaveSnapshot', - request_serializer=environments.SaveSnapshotRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['save_snapshot'] - - @property - def load_snapshot(self) -> Callable[ - [environments.LoadSnapshotRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the load snapshot method over gRPC. - - Loads a snapshot of a Cloud Composer environment. - - As a result of this operation, a snapshot of - environment's specified in LoadSnapshotRequest is loaded - into the environment. - - Returns: - Callable[[~.LoadSnapshotRequest], - 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 'load_snapshot' not in self._stubs: - self._stubs['load_snapshot'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/LoadSnapshot', - request_serializer=environments.LoadSnapshotRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['load_snapshot'] - - @property - def database_failover(self) -> Callable[ - [environments.DatabaseFailoverRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the database failover method over gRPC. - - Triggers database failover (only for highly resilient - environments). - - Returns: - Callable[[~.DatabaseFailoverRequest], - 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 'database_failover' not in self._stubs: - self._stubs['database_failover'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/DatabaseFailover', - request_serializer=environments.DatabaseFailoverRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['database_failover'] - - @property - def fetch_database_properties(self) -> Callable[ - [environments.FetchDatabasePropertiesRequest], - Awaitable[environments.FetchDatabasePropertiesResponse]]: - r"""Return a callable for the fetch database properties method over gRPC. - - Fetches database properties. - - Returns: - Callable[[~.FetchDatabasePropertiesRequest], - Awaitable[~.FetchDatabasePropertiesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'fetch_database_properties' not in self._stubs: - self._stubs['fetch_database_properties'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.Environments/FetchDatabaseProperties', - request_serializer=environments.FetchDatabasePropertiesRequest.serialize, - response_deserializer=environments.FetchDatabasePropertiesResponse.deserialize, - ) - return self._stubs['fetch_database_properties'] - - 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_environment: self._wrap_method( - self.create_environment, - default_timeout=None, - client_info=client_info, - ), - self.get_environment: self._wrap_method( - self.get_environment, - default_timeout=None, - client_info=client_info, - ), - self.list_environments: self._wrap_method( - self.list_environments, - default_timeout=None, - client_info=client_info, - ), - self.update_environment: self._wrap_method( - self.update_environment, - default_timeout=None, - client_info=client_info, - ), - self.delete_environment: self._wrap_method( - self.delete_environment, - default_timeout=None, - client_info=client_info, - ), - self.restart_web_server: self._wrap_method( - self.restart_web_server, - default_timeout=None, - client_info=client_info, - ), - self.check_upgrade: self._wrap_method( - self.check_upgrade, - default_timeout=None, - client_info=client_info, - ), - self.execute_airflow_command: self._wrap_method( - self.execute_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.stop_airflow_command: self._wrap_method( - self.stop_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.poll_airflow_command: self._wrap_method( - self.poll_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.list_workloads: self._wrap_method( - self.list_workloads, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_secret: self._wrap_method( - self.create_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_secret: self._wrap_method( - self.get_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_secrets: self._wrap_method( - self.list_user_workloads_secrets, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_secret: self._wrap_method( - self.update_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_secret: self._wrap_method( - self.delete_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_config_map: self._wrap_method( - self.create_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_config_map: self._wrap_method( - self.get_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_config_maps: self._wrap_method( - self.list_user_workloads_config_maps, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_config_map: self._wrap_method( - self.update_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_config_map: self._wrap_method( - self.delete_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.save_snapshot: self._wrap_method( - self.save_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.load_snapshot: self._wrap_method( - self.load_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.database_failover: self._wrap_method( - self.database_failover, - default_timeout=None, - client_info=client_info, - ), - self.fetch_database_properties: self._wrap_method( - self.fetch_database_properties, - 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 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__ = ( - 'EnvironmentsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py deleted file mode 100644 index f29b846f82fe..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py +++ /dev/null @@ -1,4862 +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.orchestration.airflow.service_v1beta1.types import environments -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseEnvironmentsRestTransport -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 EnvironmentsRestInterceptor: - """Interceptor for Environments. - - 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 EnvironmentsRestTransport. - - .. code-block:: python - class MyCustomEnvironmentsInterceptor(EnvironmentsRestInterceptor): - def pre_check_upgrade(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_check_upgrade(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_user_workloads_config_map(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_user_workloads_config_map(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_user_workloads_secret(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_user_workloads_secret(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_database_failover(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_database_failover(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_user_workloads_config_map(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_user_workloads_secret(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_execute_airflow_command(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_execute_airflow_command(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_fetch_database_properties(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_fetch_database_properties(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_user_workloads_config_map(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_user_workloads_config_map(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_user_workloads_secret(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_user_workloads_secret(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_environments(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_environments(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_user_workloads_config_maps(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_user_workloads_config_maps(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_user_workloads_secrets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_user_workloads_secrets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_workloads(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_workloads(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_load_snapshot(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_load_snapshot(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_poll_airflow_command(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_poll_airflow_command(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_restart_web_server(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_restart_web_server(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_save_snapshot(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_save_snapshot(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_stop_airflow_command(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_stop_airflow_command(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_environment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_environment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_user_workloads_config_map(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_user_workloads_config_map(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_user_workloads_secret(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_user_workloads_secret(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EnvironmentsRestTransport(interceptor=MyCustomEnvironmentsInterceptor()) - client = EnvironmentsClient(transport=transport) - - - """ - def pre_check_upgrade(self, request: environments.CheckUpgradeRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CheckUpgradeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for check_upgrade - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_check_upgrade(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for check_upgrade - - DEPRECATED. Please use the `post_check_upgrade_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_check_upgrade` interceptor runs - before the `post_check_upgrade_with_metadata` interceptor. - """ - return response - - def post_check_upgrade_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for check_upgrade - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_check_upgrade_with_metadata` - interceptor in new development instead of the `post_check_upgrade` interceptor. - When both interceptors are used, this `post_check_upgrade_with_metadata` interceptor runs after the - `post_check_upgrade` interceptor. The (possibly modified) response returned by - `post_check_upgrade` will be passed to - `post_check_upgrade_with_metadata`. - """ - return response, metadata - - def pre_create_environment(self, request: environments.CreateEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_create_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_environment - - DEPRECATED. Please use the `post_create_environment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_create_environment` interceptor runs - before the `post_create_environment_with_metadata` interceptor. - """ - return response - - def post_create_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_environment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_create_environment_with_metadata` - interceptor in new development instead of the `post_create_environment` interceptor. - When both interceptors are used, this `post_create_environment_with_metadata` interceptor runs after the - `post_create_environment` interceptor. The (possibly modified) response returned by - `post_create_environment` will be passed to - `post_create_environment_with_metadata`. - """ - return response, metadata - - def pre_create_user_workloads_config_map(self, request: environments.CreateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_user_workloads_config_map - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_create_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: - """Post-rpc interceptor for create_user_workloads_config_map - - DEPRECATED. Please use the `post_create_user_workloads_config_map_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_create_user_workloads_config_map` interceptor runs - before the `post_create_user_workloads_config_map_with_metadata` interceptor. - """ - return response - - def post_create_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_user_workloads_config_map - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_create_user_workloads_config_map_with_metadata` - interceptor in new development instead of the `post_create_user_workloads_config_map` interceptor. - When both interceptors are used, this `post_create_user_workloads_config_map_with_metadata` interceptor runs after the - `post_create_user_workloads_config_map` interceptor. The (possibly modified) response returned by - `post_create_user_workloads_config_map` will be passed to - `post_create_user_workloads_config_map_with_metadata`. - """ - return response, metadata - - def pre_create_user_workloads_secret(self, request: environments.CreateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.CreateUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_user_workloads_secret - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_create_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: - """Post-rpc interceptor for create_user_workloads_secret - - DEPRECATED. Please use the `post_create_user_workloads_secret_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_create_user_workloads_secret` interceptor runs - before the `post_create_user_workloads_secret_with_metadata` interceptor. - """ - return response - - def post_create_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_user_workloads_secret - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_create_user_workloads_secret_with_metadata` - interceptor in new development instead of the `post_create_user_workloads_secret` interceptor. - When both interceptors are used, this `post_create_user_workloads_secret_with_metadata` interceptor runs after the - `post_create_user_workloads_secret` interceptor. The (possibly modified) response returned by - `post_create_user_workloads_secret` will be passed to - `post_create_user_workloads_secret_with_metadata`. - """ - return response, metadata - - def pre_database_failover(self, request: environments.DatabaseFailoverRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DatabaseFailoverRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for database_failover - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_database_failover(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for database_failover - - DEPRECATED. Please use the `post_database_failover_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_database_failover` interceptor runs - before the `post_database_failover_with_metadata` interceptor. - """ - return response - - def post_database_failover_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for database_failover - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_database_failover_with_metadata` - interceptor in new development instead of the `post_database_failover` interceptor. - When both interceptors are used, this `post_database_failover_with_metadata` interceptor runs after the - `post_database_failover` interceptor. The (possibly modified) response returned by - `post_database_failover` will be passed to - `post_database_failover_with_metadata`. - """ - return response, metadata - - def pre_delete_environment(self, request: environments.DeleteEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_delete_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_environment - - DEPRECATED. Please use the `post_delete_environment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_delete_environment` interceptor runs - before the `post_delete_environment_with_metadata` interceptor. - """ - return response - - def post_delete_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for delete_environment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_delete_environment_with_metadata` - interceptor in new development instead of the `post_delete_environment` interceptor. - When both interceptors are used, this `post_delete_environment_with_metadata` interceptor runs after the - `post_delete_environment` interceptor. The (possibly modified) response returned by - `post_delete_environment` will be passed to - `post_delete_environment_with_metadata`. - """ - return response, metadata - - def pre_delete_user_workloads_config_map(self, request: environments.DeleteUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_user_workloads_config_map - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def pre_delete_user_workloads_secret(self, request: environments.DeleteUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.DeleteUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_user_workloads_secret - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def pre_execute_airflow_command(self, request: environments.ExecuteAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ExecuteAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for execute_airflow_command - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_execute_airflow_command(self, response: environments.ExecuteAirflowCommandResponse) -> environments.ExecuteAirflowCommandResponse: - """Post-rpc interceptor for execute_airflow_command - - DEPRECATED. Please use the `post_execute_airflow_command_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_execute_airflow_command` interceptor runs - before the `post_execute_airflow_command_with_metadata` interceptor. - """ - return response - - def post_execute_airflow_command_with_metadata(self, response: environments.ExecuteAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ExecuteAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for execute_airflow_command - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_execute_airflow_command_with_metadata` - interceptor in new development instead of the `post_execute_airflow_command` interceptor. - When both interceptors are used, this `post_execute_airflow_command_with_metadata` interceptor runs after the - `post_execute_airflow_command` interceptor. The (possibly modified) response returned by - `post_execute_airflow_command` will be passed to - `post_execute_airflow_command_with_metadata`. - """ - return response, metadata - - def pre_fetch_database_properties(self, request: environments.FetchDatabasePropertiesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.FetchDatabasePropertiesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for fetch_database_properties - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_fetch_database_properties(self, response: environments.FetchDatabasePropertiesResponse) -> environments.FetchDatabasePropertiesResponse: - """Post-rpc interceptor for fetch_database_properties - - DEPRECATED. Please use the `post_fetch_database_properties_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_fetch_database_properties` interceptor runs - before the `post_fetch_database_properties_with_metadata` interceptor. - """ - return response - - def post_fetch_database_properties_with_metadata(self, response: environments.FetchDatabasePropertiesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.FetchDatabasePropertiesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for fetch_database_properties - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_fetch_database_properties_with_metadata` - interceptor in new development instead of the `post_fetch_database_properties` interceptor. - When both interceptors are used, this `post_fetch_database_properties_with_metadata` interceptor runs after the - `post_fetch_database_properties` interceptor. The (possibly modified) response returned by - `post_fetch_database_properties` will be passed to - `post_fetch_database_properties_with_metadata`. - """ - return response, metadata - - def pre_get_environment(self, request: environments.GetEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_environment(self, response: environments.Environment) -> environments.Environment: - """Post-rpc interceptor for get_environment - - DEPRECATED. Please use the `post_get_environment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_get_environment` interceptor runs - before the `post_get_environment_with_metadata` interceptor. - """ - return response - - def post_get_environment_with_metadata(self, response: environments.Environment, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.Environment, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_environment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_get_environment_with_metadata` - interceptor in new development instead of the `post_get_environment` interceptor. - When both interceptors are used, this `post_get_environment_with_metadata` interceptor runs after the - `post_get_environment` interceptor. The (possibly modified) response returned by - `post_get_environment` will be passed to - `post_get_environment_with_metadata`. - """ - return response, metadata - - def pre_get_user_workloads_config_map(self, request: environments.GetUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_user_workloads_config_map - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: - """Post-rpc interceptor for get_user_workloads_config_map - - DEPRECATED. Please use the `post_get_user_workloads_config_map_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_get_user_workloads_config_map` interceptor runs - before the `post_get_user_workloads_config_map_with_metadata` interceptor. - """ - return response - - def post_get_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_user_workloads_config_map - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_get_user_workloads_config_map_with_metadata` - interceptor in new development instead of the `post_get_user_workloads_config_map` interceptor. - When both interceptors are used, this `post_get_user_workloads_config_map_with_metadata` interceptor runs after the - `post_get_user_workloads_config_map` interceptor. The (possibly modified) response returned by - `post_get_user_workloads_config_map` will be passed to - `post_get_user_workloads_config_map_with_metadata`. - """ - return response, metadata - - def pre_get_user_workloads_secret(self, request: environments.GetUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.GetUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_user_workloads_secret - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_get_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: - """Post-rpc interceptor for get_user_workloads_secret - - DEPRECATED. Please use the `post_get_user_workloads_secret_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_get_user_workloads_secret` interceptor runs - before the `post_get_user_workloads_secret_with_metadata` interceptor. - """ - return response - - def post_get_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_user_workloads_secret - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_get_user_workloads_secret_with_metadata` - interceptor in new development instead of the `post_get_user_workloads_secret` interceptor. - When both interceptors are used, this `post_get_user_workloads_secret_with_metadata` interceptor runs after the - `post_get_user_workloads_secret` interceptor. The (possibly modified) response returned by - `post_get_user_workloads_secret` will be passed to - `post_get_user_workloads_secret_with_metadata`. - """ - return response, metadata - - def pre_list_environments(self, request: environments.ListEnvironmentsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListEnvironmentsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_environments - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_environments(self, response: environments.ListEnvironmentsResponse) -> environments.ListEnvironmentsResponse: - """Post-rpc interceptor for list_environments - - DEPRECATED. Please use the `post_list_environments_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_list_environments` interceptor runs - before the `post_list_environments_with_metadata` interceptor. - """ - return response - - def post_list_environments_with_metadata(self, response: environments.ListEnvironmentsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListEnvironmentsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_environments - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_list_environments_with_metadata` - interceptor in new development instead of the `post_list_environments` interceptor. - When both interceptors are used, this `post_list_environments_with_metadata` interceptor runs after the - `post_list_environments` interceptor. The (possibly modified) response returned by - `post_list_environments` will be passed to - `post_list_environments_with_metadata`. - """ - return response, metadata - - def pre_list_user_workloads_config_maps(self, request: environments.ListUserWorkloadsConfigMapsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsConfigMapsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_user_workloads_config_maps - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_user_workloads_config_maps(self, response: environments.ListUserWorkloadsConfigMapsResponse) -> environments.ListUserWorkloadsConfigMapsResponse: - """Post-rpc interceptor for list_user_workloads_config_maps - - DEPRECATED. Please use the `post_list_user_workloads_config_maps_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_list_user_workloads_config_maps` interceptor runs - before the `post_list_user_workloads_config_maps_with_metadata` interceptor. - """ - return response - - def post_list_user_workloads_config_maps_with_metadata(self, response: environments.ListUserWorkloadsConfigMapsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsConfigMapsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_user_workloads_config_maps - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_list_user_workloads_config_maps_with_metadata` - interceptor in new development instead of the `post_list_user_workloads_config_maps` interceptor. - When both interceptors are used, this `post_list_user_workloads_config_maps_with_metadata` interceptor runs after the - `post_list_user_workloads_config_maps` interceptor. The (possibly modified) response returned by - `post_list_user_workloads_config_maps` will be passed to - `post_list_user_workloads_config_maps_with_metadata`. - """ - return response, metadata - - def pre_list_user_workloads_secrets(self, request: environments.ListUserWorkloadsSecretsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsSecretsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_user_workloads_secrets - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_user_workloads_secrets(self, response: environments.ListUserWorkloadsSecretsResponse) -> environments.ListUserWorkloadsSecretsResponse: - """Post-rpc interceptor for list_user_workloads_secrets - - DEPRECATED. Please use the `post_list_user_workloads_secrets_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_list_user_workloads_secrets` interceptor runs - before the `post_list_user_workloads_secrets_with_metadata` interceptor. - """ - return response - - def post_list_user_workloads_secrets_with_metadata(self, response: environments.ListUserWorkloadsSecretsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListUserWorkloadsSecretsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_user_workloads_secrets - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_list_user_workloads_secrets_with_metadata` - interceptor in new development instead of the `post_list_user_workloads_secrets` interceptor. - When both interceptors are used, this `post_list_user_workloads_secrets_with_metadata` interceptor runs after the - `post_list_user_workloads_secrets` interceptor. The (possibly modified) response returned by - `post_list_user_workloads_secrets` will be passed to - `post_list_user_workloads_secrets_with_metadata`. - """ - return response, metadata - - def pre_list_workloads(self, request: environments.ListWorkloadsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListWorkloadsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_workloads - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_list_workloads(self, response: environments.ListWorkloadsResponse) -> environments.ListWorkloadsResponse: - """Post-rpc interceptor for list_workloads - - DEPRECATED. Please use the `post_list_workloads_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_list_workloads` interceptor runs - before the `post_list_workloads_with_metadata` interceptor. - """ - return response - - def post_list_workloads_with_metadata(self, response: environments.ListWorkloadsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.ListWorkloadsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_workloads - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_list_workloads_with_metadata` - interceptor in new development instead of the `post_list_workloads` interceptor. - When both interceptors are used, this `post_list_workloads_with_metadata` interceptor runs after the - `post_list_workloads` interceptor. The (possibly modified) response returned by - `post_list_workloads` will be passed to - `post_list_workloads_with_metadata`. - """ - return response, metadata - - def pre_load_snapshot(self, request: environments.LoadSnapshotRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.LoadSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for load_snapshot - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_load_snapshot(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for load_snapshot - - DEPRECATED. Please use the `post_load_snapshot_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_load_snapshot` interceptor runs - before the `post_load_snapshot_with_metadata` interceptor. - """ - return response - - def post_load_snapshot_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for load_snapshot - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_load_snapshot_with_metadata` - interceptor in new development instead of the `post_load_snapshot` interceptor. - When both interceptors are used, this `post_load_snapshot_with_metadata` interceptor runs after the - `post_load_snapshot` interceptor. The (possibly modified) response returned by - `post_load_snapshot` will be passed to - `post_load_snapshot_with_metadata`. - """ - return response, metadata - - def pre_poll_airflow_command(self, request: environments.PollAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.PollAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for poll_airflow_command - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_poll_airflow_command(self, response: environments.PollAirflowCommandResponse) -> environments.PollAirflowCommandResponse: - """Post-rpc interceptor for poll_airflow_command - - DEPRECATED. Please use the `post_poll_airflow_command_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_poll_airflow_command` interceptor runs - before the `post_poll_airflow_command_with_metadata` interceptor. - """ - return response - - def post_poll_airflow_command_with_metadata(self, response: environments.PollAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.PollAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for poll_airflow_command - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_poll_airflow_command_with_metadata` - interceptor in new development instead of the `post_poll_airflow_command` interceptor. - When both interceptors are used, this `post_poll_airflow_command_with_metadata` interceptor runs after the - `post_poll_airflow_command` interceptor. The (possibly modified) response returned by - `post_poll_airflow_command` will be passed to - `post_poll_airflow_command_with_metadata`. - """ - return response, metadata - - def pre_restart_web_server(self, request: environments.RestartWebServerRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.RestartWebServerRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for restart_web_server - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_restart_web_server(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for restart_web_server - - DEPRECATED. Please use the `post_restart_web_server_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_restart_web_server` interceptor runs - before the `post_restart_web_server_with_metadata` interceptor. - """ - return response - - def post_restart_web_server_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for restart_web_server - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_restart_web_server_with_metadata` - interceptor in new development instead of the `post_restart_web_server` interceptor. - When both interceptors are used, this `post_restart_web_server_with_metadata` interceptor runs after the - `post_restart_web_server` interceptor. The (possibly modified) response returned by - `post_restart_web_server` will be passed to - `post_restart_web_server_with_metadata`. - """ - return response, metadata - - def pre_save_snapshot(self, request: environments.SaveSnapshotRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.SaveSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for save_snapshot - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_save_snapshot(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for save_snapshot - - DEPRECATED. Please use the `post_save_snapshot_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_save_snapshot` interceptor runs - before the `post_save_snapshot_with_metadata` interceptor. - """ - return response - - def post_save_snapshot_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for save_snapshot - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_save_snapshot_with_metadata` - interceptor in new development instead of the `post_save_snapshot` interceptor. - When both interceptors are used, this `post_save_snapshot_with_metadata` interceptor runs after the - `post_save_snapshot` interceptor. The (possibly modified) response returned by - `post_save_snapshot` will be passed to - `post_save_snapshot_with_metadata`. - """ - return response, metadata - - def pre_stop_airflow_command(self, request: environments.StopAirflowCommandRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.StopAirflowCommandRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for stop_airflow_command - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_stop_airflow_command(self, response: environments.StopAirflowCommandResponse) -> environments.StopAirflowCommandResponse: - """Post-rpc interceptor for stop_airflow_command - - DEPRECATED. Please use the `post_stop_airflow_command_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_stop_airflow_command` interceptor runs - before the `post_stop_airflow_command_with_metadata` interceptor. - """ - return response - - def post_stop_airflow_command_with_metadata(self, response: environments.StopAirflowCommandResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.StopAirflowCommandResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for stop_airflow_command - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_stop_airflow_command_with_metadata` - interceptor in new development instead of the `post_stop_airflow_command` interceptor. - When both interceptors are used, this `post_stop_airflow_command_with_metadata` interceptor runs after the - `post_stop_airflow_command` interceptor. The (possibly modified) response returned by - `post_stop_airflow_command` will be passed to - `post_stop_airflow_command_with_metadata`. - """ - return response, metadata - - def pre_update_environment(self, request: environments.UpdateEnvironmentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateEnvironmentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_environment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_update_environment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_environment - - DEPRECATED. Please use the `post_update_environment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_update_environment` interceptor runs - before the `post_update_environment_with_metadata` interceptor. - """ - return response - - def post_update_environment_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_environment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_update_environment_with_metadata` - interceptor in new development instead of the `post_update_environment` interceptor. - When both interceptors are used, this `post_update_environment_with_metadata` interceptor runs after the - `post_update_environment` interceptor. The (possibly modified) response returned by - `post_update_environment` will be passed to - `post_update_environment_with_metadata`. - """ - return response, metadata - - def pre_update_user_workloads_config_map(self, request: environments.UpdateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_user_workloads_config_map - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_update_user_workloads_config_map(self, response: environments.UserWorkloadsConfigMap) -> environments.UserWorkloadsConfigMap: - """Post-rpc interceptor for update_user_workloads_config_map - - DEPRECATED. Please use the `post_update_user_workloads_config_map_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_update_user_workloads_config_map` interceptor runs - before the `post_update_user_workloads_config_map_with_metadata` interceptor. - """ - return response - - def post_update_user_workloads_config_map_with_metadata(self, response: environments.UserWorkloadsConfigMap, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsConfigMap, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_user_workloads_config_map - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_update_user_workloads_config_map_with_metadata` - interceptor in new development instead of the `post_update_user_workloads_config_map` interceptor. - When both interceptors are used, this `post_update_user_workloads_config_map_with_metadata` interceptor runs after the - `post_update_user_workloads_config_map` interceptor. The (possibly modified) response returned by - `post_update_user_workloads_config_map` will be passed to - `post_update_user_workloads_config_map_with_metadata`. - """ - return response, metadata - - def pre_update_user_workloads_secret(self, request: environments.UpdateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UpdateUserWorkloadsSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_user_workloads_secret - - Override in a subclass to manipulate the request or metadata - before they are sent to the Environments server. - """ - return request, metadata - - def post_update_user_workloads_secret(self, response: environments.UserWorkloadsSecret) -> environments.UserWorkloadsSecret: - """Post-rpc interceptor for update_user_workloads_secret - - DEPRECATED. Please use the `post_update_user_workloads_secret_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Environments server but before - it is returned to user code. This `post_update_user_workloads_secret` interceptor runs - before the `post_update_user_workloads_secret_with_metadata` interceptor. - """ - return response - - def post_update_user_workloads_secret_with_metadata(self, response: environments.UserWorkloadsSecret, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[environments.UserWorkloadsSecret, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_user_workloads_secret - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Environments server but before it is returned to user code. - - We recommend only using this `post_update_user_workloads_secret_with_metadata` - interceptor in new development instead of the `post_update_user_workloads_secret` interceptor. - When both interceptors are used, this `post_update_user_workloads_secret_with_metadata` interceptor runs after the - `post_update_user_workloads_secret` interceptor. The (possibly modified) response returned by - `post_update_user_workloads_secret` will be passed to - `post_update_user_workloads_secret_with_metadata`. - """ - return response, metadata - - 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 Environments 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 Environments 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 Environments 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 Environments 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 Environments 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 Environments server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class EnvironmentsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EnvironmentsRestInterceptor - - -class EnvironmentsRestTransport(_BaseEnvironmentsRestTransport): - """REST backend synchronous transport for Environments. - - Managed Apache Airflow Environments. - - 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 = 'composer.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[EnvironmentsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'composer.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 EnvironmentsRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1beta1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CheckUpgrade(_BaseEnvironmentsRestTransport._BaseCheckUpgrade, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.CheckUpgrade") - - @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: environments.CheckUpgradeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the check upgrade method over HTTP. - - Args: - request (~.environments.CheckUpgradeRequest): - The request object. Request to check whether image - upgrade will succeed. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_http_options() - - request, metadata = self._interceptor.pre_check_upgrade(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseCheckUpgrade._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.CheckUpgrade", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "CheckUpgrade", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._CheckUpgrade._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_check_upgrade(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_check_upgrade_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.check_upgrade", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "CheckUpgrade", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateEnvironment(_BaseEnvironmentsRestTransport._BaseCreateEnvironment, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.CreateEnvironment") - - @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: environments.CreateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create environment method over HTTP. - - Args: - request (~.environments.CreateEnvironmentRequest): - The request object. Create a new environment. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_http_options() - - request, metadata = self._interceptor.pre_create_environment(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseCreateEnvironment._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.CreateEnvironment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "CreateEnvironment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._CreateEnvironment._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_environment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_environment_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_environment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "CreateEnvironment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.CreateUserWorkloadsConfigMap") - - @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: environments.CreateUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsConfigMap: - r"""Call the create user workloads - config map method over HTTP. - - Args: - request (~.environments.CreateUserWorkloadsConfigMapRequest): - The request object. Create user workloads ConfigMap - request. - retry (google.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: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_http_options() - - request, metadata = self._interceptor.pre_create_user_workloads_config_map(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.CreateUserWorkloadsConfigMap", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "CreateUserWorkloadsConfigMap", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._CreateUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() - pb_resp = environments.UserWorkloadsConfigMap.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_user_workloads_config_map(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_user_workloads_config_map_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_user_workloads_config_map", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "CreateUserWorkloadsConfigMap", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.CreateUserWorkloadsSecret") - - @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: environments.CreateUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsSecret: - r"""Call the create user workloads - secret method over HTTP. - - Args: - request (~.environments.CreateUserWorkloadsSecretRequest): - The request object. Create user workloads Secret request. - retry (google.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: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_http_options() - - request, metadata = self._interceptor.pre_create_user_workloads_secret(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.CreateUserWorkloadsSecret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "CreateUserWorkloadsSecret", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._CreateUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() - pb_resp = environments.UserWorkloadsSecret.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_user_workloads_secret(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_user_workloads_secret_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_user_workloads_secret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "CreateUserWorkloadsSecret", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DatabaseFailover(_BaseEnvironmentsRestTransport._BaseDatabaseFailover, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.DatabaseFailover") - - @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: environments.DatabaseFailoverRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the database failover method over HTTP. - - Args: - request (~.environments.DatabaseFailoverRequest): - The request object. Request to trigger database failover - (only for highly resilient - environments). - retry (google.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 = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_http_options() - - request, metadata = self._interceptor.pre_database_failover(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseDatabaseFailover._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.DatabaseFailover", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "DatabaseFailover", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._DatabaseFailover._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_database_failover(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_database_failover_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.database_failover", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "DatabaseFailover", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteEnvironment(_BaseEnvironmentsRestTransport._BaseDeleteEnvironment, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.DeleteEnvironment") - - @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: environments.DeleteEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete environment method over HTTP. - - Args: - request (~.environments.DeleteEnvironmentRequest): - The request object. Delete an environment. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_http_options() - - request, metadata = self._interceptor.pre_delete_environment(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseDeleteEnvironment._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.DeleteEnvironment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "DeleteEnvironment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._DeleteEnvironment._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_environment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_environment_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.delete_environment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "DeleteEnvironment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.DeleteUserWorkloadsConfigMap") - - @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: environments.DeleteUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete user workloads - config map method over HTTP. - - Args: - request (~.environments.DeleteUserWorkloadsConfigMapRequest): - The request object. Delete user workloads ConfigMap - request. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_http_options() - - request, metadata = self._interceptor.pre_delete_user_workloads_config_map(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.DeleteUserWorkloadsConfigMap", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "DeleteUserWorkloadsConfigMap", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._DeleteUserWorkloadsConfigMap._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) - - class _DeleteUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.DeleteUserWorkloadsSecret") - - @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: environments.DeleteUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete user workloads - secret method over HTTP. - - Args: - request (~.environments.DeleteUserWorkloadsSecretRequest): - The request object. Delete user workloads Secret request. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_http_options() - - request, metadata = self._interceptor.pre_delete_user_workloads_secret(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.DeleteUserWorkloadsSecret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "DeleteUserWorkloadsSecret", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._DeleteUserWorkloadsSecret._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) - - class _ExecuteAirflowCommand(_BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.ExecuteAirflowCommand") - - @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: environments.ExecuteAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.ExecuteAirflowCommandResponse: - r"""Call the execute airflow command method over HTTP. - - Args: - request (~.environments.ExecuteAirflowCommandRequest): - The request object. Execute Airflow Command request. - retry (google.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: - ~.environments.ExecuteAirflowCommandResponse: - Response to - ExecuteAirflowCommandRequest. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_http_options() - - request, metadata = self._interceptor.pre_execute_airflow_command(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseExecuteAirflowCommand._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ExecuteAirflowCommand", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ExecuteAirflowCommand", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._ExecuteAirflowCommand._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 = environments.ExecuteAirflowCommandResponse() - pb_resp = environments.ExecuteAirflowCommandResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_execute_airflow_command(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_execute_airflow_command_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.ExecuteAirflowCommandResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.execute_airflow_command", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ExecuteAirflowCommand", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _FetchDatabaseProperties(_BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.FetchDatabaseProperties") - - @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: environments.FetchDatabasePropertiesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.FetchDatabasePropertiesResponse: - r"""Call the fetch database properties method over HTTP. - - Args: - request (~.environments.FetchDatabasePropertiesRequest): - The request object. Request to fetch properties of - environment's database. - retry (google.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: - ~.environments.FetchDatabasePropertiesResponse: - Response for - FetchDatabasePropertiesRequest. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_http_options() - - request, metadata = self._interceptor.pre_fetch_database_properties(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.FetchDatabaseProperties", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "FetchDatabaseProperties", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._FetchDatabaseProperties._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 = environments.FetchDatabasePropertiesResponse() - pb_resp = environments.FetchDatabasePropertiesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_fetch_database_properties(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_fetch_database_properties_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.FetchDatabasePropertiesResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.fetch_database_properties", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "FetchDatabaseProperties", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetEnvironment(_BaseEnvironmentsRestTransport._BaseGetEnvironment, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.GetEnvironment") - - @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: environments.GetEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.Environment: - r"""Call the get environment method over HTTP. - - Args: - request (~.environments.GetEnvironmentRequest): - The request object. Get an environment. - retry (google.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: - ~.environments.Environment: - An environment for running - orchestration tasks. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_http_options() - - request, metadata = self._interceptor.pre_get_environment(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseGetEnvironment._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseGetEnvironment._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.GetEnvironment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "GetEnvironment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._GetEnvironment._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 = environments.Environment() - pb_resp = environments.Environment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_environment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_environment_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.Environment.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_environment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "GetEnvironment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.GetUserWorkloadsConfigMap") - - @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: environments.GetUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsConfigMap: - r"""Call the get user workloads config - map method over HTTP. - - Args: - request (~.environments.GetUserWorkloadsConfigMapRequest): - The request object. Get user workloads ConfigMap request. - retry (google.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: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_http_options() - - request, metadata = self._interceptor.pre_get_user_workloads_config_map(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.GetUserWorkloadsConfigMap", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "GetUserWorkloadsConfigMap", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._GetUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() - pb_resp = environments.UserWorkloadsConfigMap.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_user_workloads_config_map(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_user_workloads_config_map_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_user_workloads_config_map", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "GetUserWorkloadsConfigMap", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.GetUserWorkloadsSecret") - - @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: environments.GetUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsSecret: - r"""Call the get user workloads secret method over HTTP. - - Args: - request (~.environments.GetUserWorkloadsSecretRequest): - The request object. Get user workloads Secret request. - retry (google.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: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_http_options() - - request, metadata = self._interceptor.pre_get_user_workloads_secret(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.GetUserWorkloadsSecret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "GetUserWorkloadsSecret", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._GetUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() - pb_resp = environments.UserWorkloadsSecret.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_user_workloads_secret(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_user_workloads_secret_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_user_workloads_secret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "GetUserWorkloadsSecret", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListEnvironments(_BaseEnvironmentsRestTransport._BaseListEnvironments, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.ListEnvironments") - - @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: environments.ListEnvironmentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.ListEnvironmentsResponse: - r"""Call the list environments method over HTTP. - - Args: - request (~.environments.ListEnvironmentsRequest): - The request object. List environments in a project and - location. - retry (google.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: - ~.environments.ListEnvironmentsResponse: - The environments in a project and - location. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseListEnvironments._get_http_options() - - request, metadata = self._interceptor.pre_list_environments(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseListEnvironments._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseListEnvironments._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ListEnvironments", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ListEnvironments", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._ListEnvironments._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 = environments.ListEnvironmentsResponse() - pb_resp = environments.ListEnvironmentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_environments(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_environments_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.ListEnvironmentsResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_environments", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ListEnvironments", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListUserWorkloadsConfigMaps(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.ListUserWorkloadsConfigMaps") - - @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: environments.ListUserWorkloadsConfigMapsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.ListUserWorkloadsConfigMapsResponse: - r"""Call the list user workloads - config maps method over HTTP. - - Args: - request (~.environments.ListUserWorkloadsConfigMapsRequest): - The request object. List user workloads ConfigMaps - request. - retry (google.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: - ~.environments.ListUserWorkloadsConfigMapsResponse: - The user workloads ConfigMaps for a - given environment. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_http_options() - - request, metadata = self._interceptor.pre_list_user_workloads_config_maps(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ListUserWorkloadsConfigMaps", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ListUserWorkloadsConfigMaps", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._ListUserWorkloadsConfigMaps._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 = environments.ListUserWorkloadsConfigMapsResponse() - pb_resp = environments.ListUserWorkloadsConfigMapsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_user_workloads_config_maps(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_user_workloads_config_maps_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.ListUserWorkloadsConfigMapsResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_user_workloads_config_maps", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ListUserWorkloadsConfigMaps", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListUserWorkloadsSecrets(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.ListUserWorkloadsSecrets") - - @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: environments.ListUserWorkloadsSecretsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.ListUserWorkloadsSecretsResponse: - r"""Call the list user workloads - secrets method over HTTP. - - Args: - request (~.environments.ListUserWorkloadsSecretsRequest): - The request object. List user workloads Secrets request. - retry (google.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: - ~.environments.ListUserWorkloadsSecretsResponse: - The user workloads Secrets for a - given environment. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_http_options() - - request, metadata = self._interceptor.pre_list_user_workloads_secrets(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ListUserWorkloadsSecrets", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ListUserWorkloadsSecrets", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._ListUserWorkloadsSecrets._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 = environments.ListUserWorkloadsSecretsResponse() - pb_resp = environments.ListUserWorkloadsSecretsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_user_workloads_secrets(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_user_workloads_secrets_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.ListUserWorkloadsSecretsResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_user_workloads_secrets", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ListUserWorkloadsSecrets", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListWorkloads(_BaseEnvironmentsRestTransport._BaseListWorkloads, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.ListWorkloads") - - @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: environments.ListWorkloadsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.ListWorkloadsResponse: - r"""Call the list workloads method over HTTP. - - Args: - request (~.environments.ListWorkloadsRequest): - The request object. Request for listing workloads in a - Cloud Composer environment. - retry (google.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: - ~.environments.ListWorkloadsResponse: - Response to ListWorkloadsRequest. - """ - - http_options = _BaseEnvironmentsRestTransport._BaseListWorkloads._get_http_options() - - request, metadata = self._interceptor.pre_list_workloads(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseListWorkloads._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseListWorkloads._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ListWorkloads", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ListWorkloads", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._ListWorkloads._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 = environments.ListWorkloadsResponse() - pb_resp = environments.ListWorkloadsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_workloads(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_workloads_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.ListWorkloadsResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_workloads", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ListWorkloads", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _LoadSnapshot(_BaseEnvironmentsRestTransport._BaseLoadSnapshot, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.LoadSnapshot") - - @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: environments.LoadSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the load snapshot method over HTTP. - - Args: - request (~.environments.LoadSnapshotRequest): - The request object. Request to load a snapshot into a - Cloud Composer environment. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_http_options() - - request, metadata = self._interceptor.pre_load_snapshot(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseLoadSnapshot._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.LoadSnapshot", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "LoadSnapshot", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._LoadSnapshot._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_load_snapshot(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_load_snapshot_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.load_snapshot", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "LoadSnapshot", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _PollAirflowCommand(_BaseEnvironmentsRestTransport._BasePollAirflowCommand, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.PollAirflowCommand") - - @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: environments.PollAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.PollAirflowCommandResponse: - r"""Call the poll airflow command method over HTTP. - - Args: - request (~.environments.PollAirflowCommandRequest): - The request object. Poll Airflow Command request. - retry (google.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: - ~.environments.PollAirflowCommandResponse: - Response to - PollAirflowCommandRequest. - - """ - - http_options = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_http_options() - - request, metadata = self._interceptor.pre_poll_airflow_command(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BasePollAirflowCommand._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.PollAirflowCommand", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "PollAirflowCommand", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._PollAirflowCommand._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 = environments.PollAirflowCommandResponse() - pb_resp = environments.PollAirflowCommandResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_poll_airflow_command(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_poll_airflow_command_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.PollAirflowCommandResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.poll_airflow_command", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "PollAirflowCommand", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _RestartWebServer(_BaseEnvironmentsRestTransport._BaseRestartWebServer, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.RestartWebServer") - - @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: environments.RestartWebServerRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the restart web server method over HTTP. - - Args: - request (~.environments.RestartWebServerRequest): - The request object. Restart Airflow web server. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseRestartWebServer._get_http_options() - - request, metadata = self._interceptor.pre_restart_web_server(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseRestartWebServer._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseRestartWebServer._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseRestartWebServer._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.RestartWebServer", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "RestartWebServer", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._RestartWebServer._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_restart_web_server(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_restart_web_server_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.restart_web_server", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "RestartWebServer", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _SaveSnapshot(_BaseEnvironmentsRestTransport._BaseSaveSnapshot, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.SaveSnapshot") - - @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: environments.SaveSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the save snapshot method over HTTP. - - Args: - request (~.environments.SaveSnapshotRequest): - The request object. Request to create a snapshot of a - Cloud Composer environment. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_http_options() - - request, metadata = self._interceptor.pre_save_snapshot(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseSaveSnapshot._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.SaveSnapshot", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "SaveSnapshot", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._SaveSnapshot._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_save_snapshot(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_save_snapshot_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.save_snapshot", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "SaveSnapshot", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _StopAirflowCommand(_BaseEnvironmentsRestTransport._BaseStopAirflowCommand, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.StopAirflowCommand") - - @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: environments.StopAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.StopAirflowCommandResponse: - r"""Call the stop airflow command method over HTTP. - - Args: - request (~.environments.StopAirflowCommandRequest): - The request object. Stop Airflow Command request. - retry (google.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: - ~.environments.StopAirflowCommandResponse: - Response to - StopAirflowCommandRequest. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_http_options() - - request, metadata = self._interceptor.pre_stop_airflow_command(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseStopAirflowCommand._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.StopAirflowCommand", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "StopAirflowCommand", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._StopAirflowCommand._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 = environments.StopAirflowCommandResponse() - pb_resp = environments.StopAirflowCommandResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_stop_airflow_command(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_stop_airflow_command_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.StopAirflowCommandResponse.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.stop_airflow_command", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "StopAirflowCommand", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateEnvironment(_BaseEnvironmentsRestTransport._BaseUpdateEnvironment, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.UpdateEnvironment") - - @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: environments.UpdateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update environment method over HTTP. - - Args: - request (~.environments.UpdateEnvironmentRequest): - The request object. Update an environment. - retry (google.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 = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_http_options() - - request, metadata = self._interceptor.pre_update_environment(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseUpdateEnvironment._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.UpdateEnvironment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "UpdateEnvironment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._UpdateEnvironment._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_environment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_environment_with_metadata(resp, response_metadata) - 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.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_environment", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "UpdateEnvironment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateUserWorkloadsConfigMap(_BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.UpdateUserWorkloadsConfigMap") - - @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: environments.UpdateUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsConfigMap: - r"""Call the update user workloads - config map method over HTTP. - - Args: - request (~.environments.UpdateUserWorkloadsConfigMapRequest): - The request object. Update user workloads ConfigMap - request. - retry (google.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: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_http_options() - - request, metadata = self._interceptor.pre_update_user_workloads_config_map(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsConfigMap._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.UpdateUserWorkloadsConfigMap", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "UpdateUserWorkloadsConfigMap", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._UpdateUserWorkloadsConfigMap._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 = environments.UserWorkloadsConfigMap() - pb_resp = environments.UserWorkloadsConfigMap.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_user_workloads_config_map(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_user_workloads_config_map_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsConfigMap.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_user_workloads_config_map", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "UpdateUserWorkloadsConfigMap", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateUserWorkloadsSecret(_BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.UpdateUserWorkloadsSecret") - - @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: environments.UpdateUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> environments.UserWorkloadsSecret: - r"""Call the update user workloads - secret method over HTTP. - - Args: - request (~.environments.UpdateUserWorkloadsSecretRequest): - The request object. Update user workloads Secret request. - retry (google.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: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_http_options() - - request, metadata = self._interceptor.pre_update_user_workloads_secret(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_transcoded_request(http_options, request) - - body = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._BaseUpdateUserWorkloadsSecret._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.UpdateUserWorkloadsSecret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "UpdateUserWorkloadsSecret", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._UpdateUserWorkloadsSecret._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 = environments.UserWorkloadsSecret() - pb_resp = environments.UserWorkloadsSecret.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_user_workloads_secret(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_user_workloads_secret_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = environments.UserWorkloadsSecret.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.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_user_workloads_secret", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "UpdateUserWorkloadsSecret", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def check_upgrade(self) -> Callable[ - [environments.CheckUpgradeRequest], - 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._CheckUpgrade(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_environment(self) -> Callable[ - [environments.CreateEnvironmentRequest], - 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._CreateEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_user_workloads_config_map(self) -> Callable[ - [environments.CreateUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - # 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._CreateUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_user_workloads_secret(self) -> Callable[ - [environments.CreateUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - # 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._CreateUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore - - @property - def database_failover(self) -> Callable[ - [environments.DatabaseFailoverRequest], - 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._DatabaseFailover(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_environment(self) -> Callable[ - [environments.DeleteEnvironmentRequest], - 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._DeleteEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_user_workloads_config_map(self) -> Callable[ - [environments.DeleteUserWorkloadsConfigMapRequest], - empty_pb2.Empty]: - # 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._DeleteUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_user_workloads_secret(self) -> Callable[ - [environments.DeleteUserWorkloadsSecretRequest], - empty_pb2.Empty]: - # 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._DeleteUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore - - @property - def execute_airflow_command(self) -> Callable[ - [environments.ExecuteAirflowCommandRequest], - environments.ExecuteAirflowCommandResponse]: - # 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._ExecuteAirflowCommand(self._session, self._host, self._interceptor) # type: ignore - - @property - def fetch_database_properties(self) -> Callable[ - [environments.FetchDatabasePropertiesRequest], - environments.FetchDatabasePropertiesResponse]: - # 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._FetchDatabaseProperties(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_environment(self) -> Callable[ - [environments.GetEnvironmentRequest], - environments.Environment]: - # 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._GetEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_user_workloads_config_map(self) -> Callable[ - [environments.GetUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - # 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._GetUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_user_workloads_secret(self) -> Callable[ - [environments.GetUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - # 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._GetUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_environments(self) -> Callable[ - [environments.ListEnvironmentsRequest], - environments.ListEnvironmentsResponse]: - # 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._ListEnvironments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_user_workloads_config_maps(self) -> Callable[ - [environments.ListUserWorkloadsConfigMapsRequest], - environments.ListUserWorkloadsConfigMapsResponse]: - # 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._ListUserWorkloadsConfigMaps(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_user_workloads_secrets(self) -> Callable[ - [environments.ListUserWorkloadsSecretsRequest], - environments.ListUserWorkloadsSecretsResponse]: - # 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._ListUserWorkloadsSecrets(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_workloads(self) -> Callable[ - [environments.ListWorkloadsRequest], - environments.ListWorkloadsResponse]: - # 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._ListWorkloads(self._session, self._host, self._interceptor) # type: ignore - - @property - def load_snapshot(self) -> Callable[ - [environments.LoadSnapshotRequest], - 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._LoadSnapshot(self._session, self._host, self._interceptor) # type: ignore - - @property - def poll_airflow_command(self) -> Callable[ - [environments.PollAirflowCommandRequest], - environments.PollAirflowCommandResponse]: - # 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._PollAirflowCommand(self._session, self._host, self._interceptor) # type: ignore - - @property - def restart_web_server(self) -> Callable[ - [environments.RestartWebServerRequest], - 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._RestartWebServer(self._session, self._host, self._interceptor) # type: ignore - - @property - def save_snapshot(self) -> Callable[ - [environments.SaveSnapshotRequest], - 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._SaveSnapshot(self._session, self._host, self._interceptor) # type: ignore - - @property - def stop_airflow_command(self) -> Callable[ - [environments.StopAirflowCommandRequest], - environments.StopAirflowCommandResponse]: - # 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._StopAirflowCommand(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_environment(self) -> Callable[ - [environments.UpdateEnvironmentRequest], - 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._UpdateEnvironment(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_user_workloads_config_map(self) -> Callable[ - [environments.UpdateUserWorkloadsConfigMapRequest], - environments.UserWorkloadsConfigMap]: - # 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._UpdateUserWorkloadsConfigMap(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_user_workloads_secret(self) -> Callable[ - [environments.UpdateUserWorkloadsSecretRequest], - environments.UserWorkloadsSecret]: - # 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._UpdateUserWorkloadsSecret(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseEnvironmentsRestTransport._BaseDeleteOperation, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseDeleteOperation._get_http_options() - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.DeleteOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._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(_BaseEnvironmentsRestTransport._BaseGetOperation, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.GetOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._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.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.GetOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "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(_BaseEnvironmentsRestTransport._BaseListOperations, EnvironmentsRestStub): - def __hash__(self): - return hash("EnvironmentsRestTransport.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 = _BaseEnvironmentsRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseEnvironmentsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEnvironmentsRestTransport._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.orchestration.airflow.service_v1beta1.EnvironmentsClient.ListOperations", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EnvironmentsRestTransport._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.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.ListOperations", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "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__=( - 'EnvironmentsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest_base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest_base.py deleted file mode 100644 index bf2121a26c83..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest_base.py +++ /dev/null @@ -1,1121 +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 EnvironmentsTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.orchestration.airflow.service_v1beta1.types import environments -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseEnvironmentsRestTransport(EnvironmentsTransport): - """Base REST backend transport for Environments. - - 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 = 'composer.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: 'composer.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 _BaseCheckUpgrade: - 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:checkUpgrade', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.CheckUpgradeRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateEnvironment: - 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': '/v1beta1/{parent=projects/*/locations/*}/environments', - 'body': 'environment', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.CreateEnvironmentRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateUserWorkloadsConfigMap: - 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': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', - 'body': 'user_workloads_config_map', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.CreateUserWorkloadsConfigMapRequest.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=True - ) - 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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsConfigMap._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateUserWorkloadsSecret: - 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': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', - 'body': 'user_workloads_secret', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.CreateUserWorkloadsSecretRequest.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=True - ) - 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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseCreateUserWorkloadsSecret._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDatabaseFailover: - 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:databaseFailover', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.DatabaseFailoverRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteEnvironment: - 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': '/v1beta1/{name=projects/*/locations/*/environments/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.DeleteEnvironmentRequest.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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteUserWorkloadsConfigMap: - 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': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.DeleteUserWorkloadsConfigMapRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsConfigMap._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteUserWorkloadsSecret: - 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': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.DeleteUserWorkloadsSecretRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseDeleteUserWorkloadsSecret._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseExecuteAirflowCommand: - 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:executeAirflowCommand', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.ExecuteAirflowCommandRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseFetchDatabaseProperties: - 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:fetchDatabaseProperties', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.FetchDatabasePropertiesRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseFetchDatabaseProperties._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetEnvironment: - 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': '/v1beta1/{name=projects/*/locations/*/environments/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.GetEnvironmentRequest.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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetUserWorkloadsConfigMap: - 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': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.GetUserWorkloadsConfigMapRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsConfigMap._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetUserWorkloadsSecret: - 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': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.GetUserWorkloadsSecretRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseGetUserWorkloadsSecret._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListEnvironments: - 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': '/v1beta1/{parent=projects/*/locations/*}/environments', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.ListEnvironmentsRequest.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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListUserWorkloadsConfigMaps: - 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': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.ListUserWorkloadsConfigMapsRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsConfigMaps._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListUserWorkloadsSecrets: - 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': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.ListUserWorkloadsSecretsRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseListUserWorkloadsSecrets._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListWorkloads: - 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': '/v1beta1/{parent=projects/*/locations/*/environments/*}/workloads', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.ListWorkloadsRequest.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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseListWorkloads._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseLoadSnapshot: - 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:loadSnapshot', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.LoadSnapshotRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BasePollAirflowCommand: - 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:pollAirflowCommand', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.PollAirflowCommandRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseRestartWebServer: - 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': '/v1beta1/{name=projects/*/locations/*/environments/*}:restartWebServer', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.RestartWebServerRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseSaveSnapshot: - 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:saveSnapshot', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.SaveSnapshotRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseStopAirflowCommand: - 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': '/v1beta1/{environment=projects/*/locations/*/environments/*}:stopAirflowCommand', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.StopAirflowCommandRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateEnvironment: - 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': '/v1beta1/{name=projects/*/locations/*/environments/*}', - 'body': 'environment', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.UpdateEnvironmentRequest.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=True - ) - 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=True, - )) - query_params.update(_BaseEnvironmentsRestTransport._BaseUpdateEnvironment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateUserWorkloadsConfigMap: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1beta1/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', - 'body': 'user_workloads_config_map', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.UpdateUserWorkloadsConfigMapRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateUserWorkloadsSecret: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1beta1/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', - 'body': 'user_workloads_secret', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = environments.UpdateUserWorkloadsSecretRequest.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=True - ) - 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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - 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': '/v1beta1/{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': '/v1beta1/{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': '/v1beta1/{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__=( - '_BaseEnvironmentsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/__init__.py deleted file mode 100644 index cf004e25ae3f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/__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 ImageVersionsClient -from .async_client import ImageVersionsAsyncClient - -__all__ = ( - 'ImageVersionsClient', - 'ImageVersionsAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/async_client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/async_client.py deleted file mode 100644 index a6cf483863e5..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/async_client.py +++ /dev/null @@ -1,536 +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.orchestration.airflow.service_v1beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_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.cloud.orchestration.airflow.service_v1beta1.services.image_versions import pagers -from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import ImageVersionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ImageVersionsGrpcAsyncIOTransport -from .client import ImageVersionsClient - -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 ImageVersionsAsyncClient: - """Readonly service to query available ImageVersions.""" - - _client: ImageVersionsClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ImageVersionsClient._DEFAULT_UNIVERSE - - common_billing_account_path = staticmethod(ImageVersionsClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ImageVersionsClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ImageVersionsClient.common_folder_path) - parse_common_folder_path = staticmethod(ImageVersionsClient.parse_common_folder_path) - common_organization_path = staticmethod(ImageVersionsClient.common_organization_path) - parse_common_organization_path = staticmethod(ImageVersionsClient.parse_common_organization_path) - common_project_path = staticmethod(ImageVersionsClient.common_project_path) - parse_common_project_path = staticmethod(ImageVersionsClient.parse_common_project_path) - common_location_path = staticmethod(ImageVersionsClient.common_location_path) - parse_common_location_path = staticmethod(ImageVersionsClient.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: - ImageVersionsAsyncClient: The constructed client. - """ - return ImageVersionsClient.from_service_account_info.__func__(ImageVersionsAsyncClient, 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: - ImageVersionsAsyncClient: The constructed client. - """ - return ImageVersionsClient.from_service_account_file.__func__(ImageVersionsAsyncClient, 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 ImageVersionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ImageVersionsTransport: - """Returns the transport used by the client instance. - - Returns: - ImageVersionsTransport: 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 = ImageVersionsClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ImageVersionsTransport, Callable[..., ImageVersionsTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the image versions 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,ImageVersionsTransport,Callable[..., ImageVersionsTransport]]]): - 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 ImageVersionsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ImageVersionsClient( - 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.orchestration.airflow.service_v1beta1.ImageVersionsAsyncClient`.", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "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.orchestration.airflow.service.v1beta1.ImageVersions", - "credentialsType": None, - } - ) - - async def list_image_versions(self, - request: Optional[Union[image_versions.ListImageVersionsRequest, 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.ListImageVersionsAsyncPager: - r"""List ImageVersions for provided 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.orchestration.airflow import service_v1beta1 - - async def sample_list_image_versions(): - # Create a client - client = service_v1beta1.ImageVersionsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ListImageVersionsRequest( - ) - - # Make the request - page_result = client.list_image_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest, dict]]): - The request object. List ImageVersions in a project and - location. - parent (:class:`str`): - List ImageVersions in the given - project and location, in the form: - "projects/{projectId}/locations/{locationId}" - - 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.orchestration.airflow.service_v1beta1.services.image_versions.pagers.ListImageVersionsAsyncPager: - The ImageVersions in a project and - location. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, image_versions.ListImageVersionsRequest): - request = image_versions.ListImageVersionsRequest(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_image_versions] - - # 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.ListImageVersionsAsyncPager( - method=rpc, - request=request, - response=response, - 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 __aenter__(self) -> "ImageVersionsAsyncClient": - 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__ = ( - "ImageVersionsAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py deleted file mode 100644 index d7e90206e07e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py +++ /dev/null @@ -1,897 +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 http import HTTPStatus -import json -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.orchestration.airflow.service_v1beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, 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.cloud.orchestration.airflow.service_v1beta1.services.image_versions import pagers -from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import ImageVersionsTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ImageVersionsGrpcTransport -from .transports.grpc_asyncio import ImageVersionsGrpcAsyncIOTransport -from .transports.rest import ImageVersionsRestTransport - - -class ImageVersionsClientMeta(type): - """Metaclass for the ImageVersions 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[ImageVersionsTransport]] - _transport_registry["grpc"] = ImageVersionsGrpcTransport - _transport_registry["grpc_asyncio"] = ImageVersionsGrpcAsyncIOTransport - _transport_registry["rest"] = ImageVersionsRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ImageVersionsTransport]: - """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 ImageVersionsClient(metaclass=ImageVersionsClientMeta): - """Readonly service to query available ImageVersions.""" - - @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 = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "composer.{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: - ImageVersionsClient: 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: - ImageVersionsClient: 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) -> ImageVersionsTransport: - """Returns the transport used by the client instance. - - Returns: - ImageVersionsTransport: The transport used by the client - instance. - """ - return self._transport - - @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 = ImageVersionsClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ImageVersionsClient._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 = ImageVersionsClient._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 - - def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError - ) -> None: - """Adds credential info string to error details for 401/403/404 errors. - - Args: - error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. - """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @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, ImageVersionsTransport, Callable[..., ImageVersionsTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the image versions 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,ImageVersionsTransport,Callable[..., ImageVersionsTransport]]]): - 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 ImageVersionsTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ImageVersionsClient._read_environment_variables() - self._client_cert_source = ImageVersionsClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ImageVersionsClient._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, ImageVersionsTransport) - if transport_provided: - # transport is a ImageVersionsTransport 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(ImageVersionsTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ImageVersionsClient._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[ImageVersionsTransport], Callable[..., ImageVersionsTransport]] = ( - ImageVersionsClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ImageVersionsTransport], 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.orchestration.airflow.service_v1beta1.ImageVersionsClient`.", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "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.orchestration.airflow.service.v1beta1.ImageVersions", - "credentialsType": None, - } - ) - - def list_image_versions(self, - request: Optional[Union[image_versions.ListImageVersionsRequest, 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.ListImageVersionsPager: - r"""List ImageVersions for provided 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.orchestration.airflow import service_v1beta1 - - def sample_list_image_versions(): - # Create a client - client = service_v1beta1.ImageVersionsClient() - - # Initialize request argument(s) - request = service_v1beta1.ListImageVersionsRequest( - ) - - # Make the request - page_result = client.list_image_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest, dict]): - The request object. List ImageVersions in a project and - location. - parent (str): - List ImageVersions in the given - project and location, in the form: - "projects/{projectId}/locations/{locationId}" - - 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.orchestration.airflow.service_v1beta1.services.image_versions.pagers.ListImageVersionsPager: - The ImageVersions in a project and - location. - 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. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - 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, image_versions.ListImageVersionsRequest): - request = image_versions.ListImageVersionsRequest(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_image_versions] - - # 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.ListImageVersionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ImageVersionsClient": - 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() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - 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() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - 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,) - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ImageVersionsClient", -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/pagers.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/pagers.py deleted file mode 100644 index dc3ad7dbf978..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/pagers.py +++ /dev/null @@ -1,166 +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.orchestration.airflow.service_v1beta1.types import image_versions - - -class ListImageVersionsPager: - """A pager for iterating through ``list_image_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``image_versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListImageVersions`` requests and continue to iterate - through the ``image_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse` - 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[..., image_versions.ListImageVersionsResponse], - request: image_versions.ListImageVersionsRequest, - response: image_versions.ListImageVersionsResponse, - *, - 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.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse): - 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 = image_versions.ListImageVersionsRequest(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[image_versions.ListImageVersionsResponse]: - 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[image_versions.ImageVersion]: - for page in self.pages: - yield from page.image_versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListImageVersionsAsyncPager: - """A pager for iterating through ``list_image_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``image_versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListImageVersions`` requests and continue to iterate - through the ``image_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse` - 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[image_versions.ListImageVersionsResponse]], - request: image_versions.ListImageVersionsRequest, - response: image_versions.ListImageVersionsResponse, - *, - 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.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse): - 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 = image_versions.ListImageVersionsRequest(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[image_versions.ListImageVersionsResponse]: - 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[image_versions.ImageVersion]: - async def async_generator(): - async for page in self.pages: - for response in page.image_versions: - 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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/README.rst b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/README.rst deleted file mode 100644 index 8d4dc0e29401..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ImageVersionsTransport` is the ABC for all transports. -- public child `ImageVersionsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ImageVersionsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseImageVersionsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ImageVersionsRestTransport` 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-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/__init__.py deleted file mode 100644 index 5ab47c371986..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/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 ImageVersionsTransport -from .grpc import ImageVersionsGrpcTransport -from .grpc_asyncio import ImageVersionsGrpcAsyncIOTransport -from .rest import ImageVersionsRestTransport -from .rest import ImageVersionsRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ImageVersionsTransport]] -_transport_registry['grpc'] = ImageVersionsGrpcTransport -_transport_registry['grpc_asyncio'] = ImageVersionsGrpcAsyncIOTransport -_transport_registry['rest'] = ImageVersionsRestTransport - -__all__ = ( - 'ImageVersionsTransport', - 'ImageVersionsGrpcTransport', - 'ImageVersionsGrpcAsyncIOTransport', - 'ImageVersionsRestTransport', - 'ImageVersionsRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/base.py deleted file mode 100644 index 1c402b590d25..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/base.py +++ /dev/null @@ -1,197 +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.orchestration.airflow.service_v1beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ImageVersionsTransport(abc.ABC): - """Abstract transport class for ImageVersions.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'composer.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: 'composer.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_image_versions: gapic_v1.method.wrap_method( - self.list_image_versions, - 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 list_image_versions(self) -> Callable[ - [image_versions.ListImageVersionsRequest], - Union[ - image_versions.ListImageVersionsResponse, - Awaitable[image_versions.ListImageVersionsResponse] - ]]: - 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 delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ImageVersionsTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc.py deleted file mode 100644 index f4f9c729b101..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc.py +++ /dev/null @@ -1,402 +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 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.orchestration.airflow.service_v1beta1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageVersionsTransport, 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.orchestration.airflow.service.v1beta1.ImageVersions", - "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.orchestration.airflow.service.v1beta1.ImageVersions", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ImageVersionsGrpcTransport(ImageVersionsTransport): - """gRPC backend transport for ImageVersions. - - Readonly service to query available ImageVersions. - - 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 = 'composer.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: 'composer.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] = {} - - 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 = 'composer.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 list_image_versions(self) -> Callable[ - [image_versions.ListImageVersionsRequest], - image_versions.ListImageVersionsResponse]: - r"""Return a callable for the list image versions method over gRPC. - - List ImageVersions for provided location. - - Returns: - Callable[[~.ListImageVersionsRequest], - ~.ListImageVersionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_image_versions' not in self._stubs: - self._stubs['list_image_versions'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.ImageVersions/ListImageVersions', - request_serializer=image_versions.ListImageVersionsRequest.serialize, - response_deserializer=image_versions.ListImageVersionsResponse.deserialize, - ) - return self._stubs['list_image_versions'] - - 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 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__ = ( - 'ImageVersionsGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc_asyncio.py deleted file mode 100644 index bf8fb63f15b4..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/grpc_asyncio.py +++ /dev/null @@ -1,437 +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.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.orchestration.airflow.service_v1beta1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO -from .grpc import ImageVersionsGrpcTransport - -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.orchestration.airflow.service.v1beta1.ImageVersions", - "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.orchestration.airflow.service.v1beta1.ImageVersions", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ImageVersionsGrpcAsyncIOTransport(ImageVersionsTransport): - """gRPC AsyncIO backend transport for ImageVersions. - - Readonly service to query available ImageVersions. - - 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 = 'composer.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 = 'composer.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: 'composer.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] = {} - - 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 list_image_versions(self) -> Callable[ - [image_versions.ListImageVersionsRequest], - Awaitable[image_versions.ListImageVersionsResponse]]: - r"""Return a callable for the list image versions method over gRPC. - - List ImageVersions for provided location. - - Returns: - Callable[[~.ListImageVersionsRequest], - Awaitable[~.ListImageVersionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_image_versions' not in self._stubs: - self._stubs['list_image_versions'] = self._logged_channel.unary_unary( - '/google.cloud.orchestration.airflow.service.v1beta1.ImageVersions/ListImageVersions', - request_serializer=image_versions.ListImageVersionsRequest.serialize, - response_deserializer=image_versions.ListImageVersionsResponse.deserialize, - ) - return self._stubs['list_image_versions'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_image_versions: self._wrap_method( - self.list_image_versions, - 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 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__ = ( - 'ImageVersionsGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest.py deleted file mode 100644 index 7da85d6557ac..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest.py +++ /dev/null @@ -1,742 +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 requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseImageVersionsRestTransport -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 ImageVersionsRestInterceptor: - """Interceptor for ImageVersions. - - 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 ImageVersionsRestTransport. - - .. code-block:: python - class MyCustomImageVersionsInterceptor(ImageVersionsRestInterceptor): - def pre_list_image_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_image_versions(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ImageVersionsRestTransport(interceptor=MyCustomImageVersionsInterceptor()) - client = ImageVersionsClient(transport=transport) - - - """ - def pre_list_image_versions(self, request: image_versions.ListImageVersionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_versions.ListImageVersionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_image_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the ImageVersions server. - """ - return request, metadata - - def post_list_image_versions(self, response: image_versions.ListImageVersionsResponse) -> image_versions.ListImageVersionsResponse: - """Post-rpc interceptor for list_image_versions - - DEPRECATED. Please use the `post_list_image_versions_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the ImageVersions server but before - it is returned to user code. This `post_list_image_versions` interceptor runs - before the `post_list_image_versions_with_metadata` interceptor. - """ - return response - - def post_list_image_versions_with_metadata(self, response: image_versions.ListImageVersionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[image_versions.ListImageVersionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_image_versions - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the ImageVersions server but before it is returned to user code. - - We recommend only using this `post_list_image_versions_with_metadata` - interceptor in new development instead of the `post_list_image_versions` interceptor. - When both interceptors are used, this `post_list_image_versions_with_metadata` interceptor runs after the - `post_list_image_versions` interceptor. The (possibly modified) response returned by - `post_list_image_versions` will be passed to - `post_list_image_versions_with_metadata`. - """ - return response, metadata - - 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions 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 ImageVersions server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ImageVersionsRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ImageVersionsRestInterceptor - - -class ImageVersionsRestTransport(_BaseImageVersionsRestTransport): - """REST backend synchronous transport for ImageVersions. - - Readonly service to query available ImageVersions. - - 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 = 'composer.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[ImageVersionsRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'composer.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) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ImageVersionsRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ListImageVersions(_BaseImageVersionsRestTransport._BaseListImageVersions, ImageVersionsRestStub): - def __hash__(self): - return hash("ImageVersionsRestTransport.ListImageVersions") - - @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: image_versions.ListImageVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> image_versions.ListImageVersionsResponse: - r"""Call the list image versions method over HTTP. - - Args: - request (~.image_versions.ListImageVersionsRequest): - The request object. List ImageVersions in a project and - location. - retry (google.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: - ~.image_versions.ListImageVersionsResponse: - The ImageVersions in a project and - location. - - """ - - http_options = _BaseImageVersionsRestTransport._BaseListImageVersions._get_http_options() - - request, metadata = self._interceptor.pre_list_image_versions(request, metadata) - transcoded_request = _BaseImageVersionsRestTransport._BaseListImageVersions._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseImageVersionsRestTransport._BaseListImageVersions._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.orchestration.airflow.service_v1beta1.ImageVersionsClient.ListImageVersions", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "rpcName": "ListImageVersions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ImageVersionsRestTransport._ListImageVersions._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 = image_versions.ListImageVersionsResponse() - pb_resp = image_versions.ListImageVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_image_versions(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_image_versions_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = image_versions.ListImageVersionsResponse.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.orchestration.airflow.service_v1beta1.ImageVersionsClient.list_image_versions", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "rpcName": "ListImageVersions", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def list_image_versions(self) -> Callable[ - [image_versions.ListImageVersionsRequest], - image_versions.ListImageVersionsResponse]: - # 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._ListImageVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseImageVersionsRestTransport._BaseDeleteOperation, ImageVersionsRestStub): - def __hash__(self): - return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseDeleteOperation._get_http_options() - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseImageVersionsRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1beta1.ImageVersionsClient.DeleteOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ImageVersionsRestTransport._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(_BaseImageVersionsRestTransport._BaseGetOperation, ImageVersionsRestStub): - def __hash__(self): - return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseImageVersionsRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1beta1.ImageVersionsClient.GetOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ImageVersionsRestTransport._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.orchestration.airflow.service_v1beta1.ImageVersionsAsyncClient.GetOperation", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "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(_BaseImageVersionsRestTransport._BaseListOperations, ImageVersionsRestStub): - def __hash__(self): - return hash("ImageVersionsRestTransport.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 = _BaseImageVersionsRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseImageVersionsRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseImageVersionsRestTransport._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.orchestration.airflow.service_v1beta1.ImageVersionsClient.ListOperations", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ImageVersionsRestTransport._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.orchestration.airflow.service_v1beta1.ImageVersionsAsyncClient.ListOperations", - extra = { - "serviceName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "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__=( - 'ImageVersionsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest_base.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest_base.py deleted file mode 100644 index e1d398c7a262..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/transports/rest_base.py +++ /dev/null @@ -1,196 +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 ImageVersionsTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseImageVersionsRestTransport(ImageVersionsTransport): - """Base REST backend transport for ImageVersions. - - 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 = 'composer.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: 'composer.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 _BaseListImageVersions: - 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': '/v1beta1/{parent=projects/*/locations/*}/imageVersions', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = image_versions.ListImageVersionsRequest.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=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - 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': '/v1beta1/{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': '/v1beta1/{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': '/v1beta1/{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__=( - '_BaseImageVersionsRestTransport', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py deleted file mode 100644 index 408cabedddfa..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py +++ /dev/null @@ -1,154 +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 .environments import ( - AirflowMetadataRetentionPolicyConfig, - CheckUpgradeRequest, - CheckUpgradeResponse, - CloudDataLineageIntegration, - CreateEnvironmentRequest, - CreateUserWorkloadsConfigMapRequest, - CreateUserWorkloadsSecretRequest, - DatabaseConfig, - DatabaseFailoverRequest, - DatabaseFailoverResponse, - DataRetentionConfig, - DeleteEnvironmentRequest, - DeleteUserWorkloadsConfigMapRequest, - DeleteUserWorkloadsSecretRequest, - EncryptionConfig, - Environment, - EnvironmentConfig, - ExecuteAirflowCommandRequest, - ExecuteAirflowCommandResponse, - FetchDatabasePropertiesRequest, - FetchDatabasePropertiesResponse, - GetEnvironmentRequest, - GetUserWorkloadsConfigMapRequest, - GetUserWorkloadsSecretRequest, - IPAllocationPolicy, - ListEnvironmentsRequest, - ListEnvironmentsResponse, - ListUserWorkloadsConfigMapsRequest, - ListUserWorkloadsConfigMapsResponse, - ListUserWorkloadsSecretsRequest, - ListUserWorkloadsSecretsResponse, - ListWorkloadsRequest, - ListWorkloadsResponse, - LoadSnapshotRequest, - LoadSnapshotResponse, - MaintenanceWindow, - MasterAuthorizedNetworksConfig, - NetworkingConfig, - NodeConfig, - PollAirflowCommandRequest, - PollAirflowCommandResponse, - PrivateClusterConfig, - PrivateEnvironmentConfig, - RecoveryConfig, - RestartWebServerRequest, - SaveSnapshotRequest, - SaveSnapshotResponse, - ScheduledSnapshotsConfig, - SoftwareConfig, - StopAirflowCommandRequest, - StopAirflowCommandResponse, - StorageConfig, - TaskLogsRetentionConfig, - UpdateEnvironmentRequest, - UpdateUserWorkloadsConfigMapRequest, - UpdateUserWorkloadsSecretRequest, - UserWorkloadsConfigMap, - UserWorkloadsSecret, - WebServerConfig, - WebServerNetworkAccessControl, - WorkloadsConfig, -) -from .image_versions import ( - ImageVersion, - ListImageVersionsRequest, - ListImageVersionsResponse, -) -from .operations import ( - OperationMetadata, -) - -__all__ = ( - 'AirflowMetadataRetentionPolicyConfig', - 'CheckUpgradeRequest', - 'CheckUpgradeResponse', - 'CloudDataLineageIntegration', - 'CreateEnvironmentRequest', - 'CreateUserWorkloadsConfigMapRequest', - 'CreateUserWorkloadsSecretRequest', - 'DatabaseConfig', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'DataRetentionConfig', - 'DeleteEnvironmentRequest', - 'DeleteUserWorkloadsConfigMapRequest', - 'DeleteUserWorkloadsSecretRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'GetEnvironmentRequest', - 'GetUserWorkloadsConfigMapRequest', - 'GetUserWorkloadsSecretRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'ListUserWorkloadsConfigMapsRequest', - 'ListUserWorkloadsConfigMapsResponse', - 'ListUserWorkloadsSecretsRequest', - 'ListUserWorkloadsSecretsResponse', - 'ListWorkloadsRequest', - 'ListWorkloadsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'RestartWebServerRequest', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'StorageConfig', - 'TaskLogsRetentionConfig', - 'UpdateEnvironmentRequest', - 'UpdateUserWorkloadsConfigMapRequest', - 'UpdateUserWorkloadsSecretRequest', - 'UserWorkloadsConfigMap', - 'UserWorkloadsSecret', - 'WebServerConfig', - 'WebServerNetworkAccessControl', - 'WorkloadsConfig', - 'ImageVersion', - 'ListImageVersionsRequest', - 'ListImageVersionsResponse', - 'OperationMetadata', -) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py deleted file mode 100644 index 5ec9203b3c2e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py +++ /dev/null @@ -1,3162 +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 field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.orchestration.airflow.service.v1beta1', - manifest={ - 'CreateEnvironmentRequest', - 'GetEnvironmentRequest', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'DeleteEnvironmentRequest', - 'UpdateEnvironmentRequest', - 'RestartWebServerRequest', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'CreateUserWorkloadsSecretRequest', - 'GetUserWorkloadsSecretRequest', - 'ListUserWorkloadsSecretsRequest', - 'UpdateUserWorkloadsSecretRequest', - 'DeleteUserWorkloadsSecretRequest', - 'CreateUserWorkloadsConfigMapRequest', - 'GetUserWorkloadsConfigMapRequest', - 'ListUserWorkloadsConfigMapsRequest', - 'UpdateUserWorkloadsConfigMapRequest', - 'DeleteUserWorkloadsConfigMapRequest', - 'UserWorkloadsSecret', - 'ListUserWorkloadsSecretsResponse', - 'UserWorkloadsConfigMap', - 'ListUserWorkloadsConfigMapsResponse', - 'ListWorkloadsRequest', - 'ListWorkloadsResponse', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'EnvironmentConfig', - 'WebServerNetworkAccessControl', - 'SoftwareConfig', - 'IPAllocationPolicy', - 'NodeConfig', - 'PrivateClusterConfig', - 'NetworkingConfig', - 'PrivateEnvironmentConfig', - 'DatabaseConfig', - 'WebServerConfig', - 'EncryptionConfig', - 'MaintenanceWindow', - 'WorkloadsConfig', - 'DataRetentionConfig', - 'TaskLogsRetentionConfig', - 'AirflowMetadataRetentionPolicyConfig', - 'StorageConfig', - 'RecoveryConfig', - 'ScheduledSnapshotsConfig', - 'MasterAuthorizedNetworksConfig', - 'CloudDataLineageIntegration', - 'Environment', - 'CheckUpgradeRequest', - 'CheckUpgradeResponse', - }, -) - - -class CreateEnvironmentRequest(proto.Message): - r"""Create a new environment. - - Attributes: - parent (str): - The parent must be of the form - "projects/{projectId}/locations/{locationId}". - environment (google.cloud.orchestration.airflow.service_v1beta1.types.Environment): - The environment to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - environment: 'Environment' = proto.Field( - proto.MESSAGE, - number=2, - message='Environment', - ) - - -class GetEnvironmentRequest(proto.Message): - r"""Get an environment. - - Attributes: - name (str): - The resource name of the environment to get, - in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListEnvironmentsRequest(proto.Message): - r"""List environments in a project and location. - - Attributes: - parent (str): - List environments in the given project and - location, in the form: - "projects/{projectId}/locations/{locationId}". - page_size (int): - The maximum number of environments to return. - page_token (str): - The next_page_token value returned from a previous List - 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 ListEnvironmentsResponse(proto.Message): - r"""The environments in a project and location. - - Attributes: - environments (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.Environment]): - The list of environments returned by a - ListEnvironmentsRequest. - next_page_token (str): - The page token used to query for the next - page if one exists. - """ - - @property - def raw_page(self): - return self - - environments: MutableSequence['Environment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Environment', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteEnvironmentRequest(proto.Message): - r"""Delete an environment. - - Attributes: - name (str): - The environment to delete, in the form: - - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateEnvironmentRequest(proto.Message): - r"""Update an environment. - - Attributes: - name (str): - The relative resource name of the environment - to update, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - environment (google.cloud.orchestration.airflow.service_v1beta1.types.Environment): - A patch environment. Fields specified by the ``updateMask`` - will be copied from the patch environment into the - environment under update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A comma-separated list of paths, relative to - ``Environment``, of fields to update. For example, to set - the version of scikit-learn to install in the environment to - 0.19.0 and to remove an existing installation of argparse, - the ``updateMask`` parameter would include the following two - ``paths`` values: - "config.softwareConfig.pypiPackages.scikit-learn" and - "config.softwareConfig.pypiPackages.argparse". The included - patch environment would specify the scikit-learn version as - follows: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "scikit-learn":"==0.19.0" - } - } - } - } - - Note that in the above example, any existing PyPI packages - other than scikit-learn and argparse will be unaffected. - - Only one update type may be included in a single request's - ``updateMask``. For example, one cannot update both the PyPI - packages and labels in the same request. However, it is - possible to update multiple members of a map field - simultaneously in the same request. For example, to set the - labels "label1" and "label2" while clearing "label3" - (assuming it already exists), one can provide the paths - "labels.label1", "labels.label2", and "labels.label3" and - populate the patch environment as follows: - - :: - - { - "labels":{ - "label1":"new-label1-value" - "label2":"new-label2-value" - } - } - - Note that in the above example, any existing labels that are - not included in the ``updateMask`` will be unaffected. - - It is also possible to replace an entire map field by - providing the map field's path in the ``updateMask``. The - new value of the field will be that which is provided in the - patch environment. For example, to delete all pre-existing - user-specified PyPI packages and install botocore at version - 1.7.14, the ``updateMask`` would contain the path - "config.softwareConfig.pypiPackages", and the patch - environment would be the following: - - :: - - { - "config":{ - "softwareConfig":{ - "pypiPackages":{ - "botocore":"==1.7.14" - } - } - } - } - - **Note:** Only the following fields can be updated: - - - ``config.softwareConfig.pypiPackages`` - - - Replace all custom custom PyPI packages. If a - replacement package map is not included in - ``environment``, all custom PyPI packages are cleared. - It is an error to provide both this mask and a mask - specifying an individual package. - - - ``config.softwareConfig.pypiPackages.``\ packagename - - - Update the custom PyPI package *packagename*, - preserving other packages. To delete the package, - include it in ``updateMask``, and omit the mapping for - it in - ``environment.config.softwareConfig.pypiPackages``. It - is an error to provide both a mask of this form and - the ``config.softwareConfig.pypiPackages`` mask. - - - ``labels`` - - - Replace all environment labels. If a replacement - labels map is not included in ``environment``, all - labels are cleared. It is an error to provide both - this mask and a mask specifying one or more individual - labels. - - - ``labels.``\ labelName - - - Set the label named *labelName*, while preserving - other labels. To delete the label, include it in - ``updateMask`` and omit its mapping in - ``environment.labels``. It is an error to provide both - a mask of this form and the ``labels`` mask. - - - ``config.nodeCount`` - - - Horizontally scale the number of nodes in the - environment. An integer greater than or equal to 3 - must be provided in the ``config.nodeCount`` field. - Supported for Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerNetworkAccessControl`` - - - Replace the environment's current - WebServerNetworkAccessControl. - - - ``config.softwareConfig.airflowConfigOverrides`` - - - Replace all Apache Airflow config overrides. If a - replacement config overrides map is not included in - ``environment``, all config overrides are cleared. It - is an error to provide both this mask and a mask - specifying one or more individual config overrides. - - - ``config.softwareConfig.airflowConfigOverrides.``\ section-name - - - Override the Apache Airflow config property *name* in - the section named *section*, preserving other - properties. To delete the property override, include - it in ``updateMask`` and omit its mapping in - ``environment.config.softwareConfig.airflowConfigOverrides``. - It is an error to provide both a mask of this form and - the ``config.softwareConfig.airflowConfigOverrides`` - mask. - - - ``config.softwareConfig.envVariables`` - - - Replace all environment variables. If a replacement - environment variable map is not included in - ``environment``, all custom environment variables are - cleared. - - - ``config.softwareConfig.imageVersion`` - - - Upgrade the version of the environment in-place. Refer - to ``SoftwareConfig.image_version`` for information on - how to format the new image version. Additionally, the - new image version cannot effect a version downgrade, - and must match the current image version's Composer - and Airflow major versions. Consult the `Cloud - Composer version - list `__ - for valid values. - - - ``config.softwareConfig.schedulerCount`` - - - Horizontally scale the number of schedulers in - Airflow. A positive integer not greater than the - number of nodes must be provided in the - ``config.softwareConfig.schedulerCount`` field. - Supported for Cloud Composer environments in versions - composer-1.\ *.*-airflow-2.*.*. - - - ``config.softwareConfig.cloudDataLineageIntegration`` - - - Configuration for Cloud Data Lineage integration. - - - ``config.databaseConfig.machineType`` - - - Cloud SQL machine type used by Airflow database. It - has to be one of: db-n1-standard-2, db-n1-standard-4, - db-n1-standard-8 or db-n1-standard-16. Supported for - Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.webServerConfig.machineType`` - - - Machine type on which Airflow web server is running. - It has to be one of: composer-n1-webserver-2, - composer-n1-webserver-4 or composer-n1-webserver-8. - Supported for Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - - ``config.maintenanceWindow`` - - - Maintenance window during which Cloud Composer - components may be under maintenance. - - - ``config.workloadsConfig`` - - - The workloads configuration settings for the GKE - cluster associated with the Cloud Composer - environment. Supported for Cloud Composer environments - in versions composer-2.\ *.*-airflow-*.*.\* and newer. - - - ``config.environmentSize`` - - - The size of the Cloud Composer environment. Supported - for Cloud Composer environments in versions - composer-2.\ *.*-airflow-*.*.\* and newer. - """ - - name: str = proto.Field( - proto.STRING, - number=2, - ) - environment: 'Environment' = proto.Field( - proto.MESSAGE, - number=1, - message='Environment', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class RestartWebServerRequest(proto.Message): - r"""Restart Airflow web server. - - Attributes: - name (str): - The resource name of the environment to - restart the web server for, in the form: - - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ExecuteAirflowCommandRequest(proto.Message): - r"""Execute Airflow Command request. - - Attributes: - environment (str): - The resource name of the environment in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - command (str): - Airflow command. - subcommand (str): - Airflow subcommand. - parameters (MutableSequence[str]): - Parameters for the Airflow command/subcommand as an array of - arguments. It may contain positional arguments like - ``["my-dag-id"]``, key-value parameters like - ``["--foo=bar"]`` or ``["--foo","bar"]``, or other flags - like ``["-f"]``. - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - command: str = proto.Field( - proto.STRING, - number=2, - ) - subcommand: str = proto.Field( - proto.STRING, - number=3, - ) - parameters: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -class ExecuteAirflowCommandResponse(proto.Message): - r"""Response to ExecuteAirflowCommandRequest. - - Attributes: - execution_id (str): - The unique ID of the command execution for - polling. - pod (str): - The name of the pod where the command is - executed. - pod_namespace (str): - The namespace of the pod where the command is - executed. - error (str): - Error message. Empty if there was no error. - """ - - execution_id: str = proto.Field( - proto.STRING, - number=1, - ) - pod: str = proto.Field( - proto.STRING, - number=2, - ) - pod_namespace: str = proto.Field( - proto.STRING, - number=3, - ) - error: str = proto.Field( - proto.STRING, - number=4, - ) - - -class StopAirflowCommandRequest(proto.Message): - r"""Stop Airflow Command request. - - Attributes: - environment (str): - The resource name of the environment in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - execution_id (str): - The unique ID of the command execution. - pod (str): - The name of the pod where the command is - executed. - pod_namespace (str): - The namespace of the pod where the command is - executed. - force (bool): - If true, the execution is terminated - forcefully (SIGKILL). If false, the execution is - stopped gracefully, giving it time for cleanup. - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - execution_id: str = proto.Field( - proto.STRING, - number=2, - ) - pod: str = proto.Field( - proto.STRING, - number=3, - ) - pod_namespace: str = proto.Field( - proto.STRING, - number=4, - ) - force: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class StopAirflowCommandResponse(proto.Message): - r"""Response to StopAirflowCommandRequest. - - Attributes: - is_done (bool): - Whether the execution is still running. - output (MutableSequence[str]): - Output message from stopping execution - request. - """ - - is_done: bool = proto.Field( - proto.BOOL, - number=1, - ) - output: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class PollAirflowCommandRequest(proto.Message): - r"""Poll Airflow Command request. - - Attributes: - environment (str): - The resource name of the environment in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - execution_id (str): - The unique ID of the command execution. - pod (str): - The name of the pod where the command is - executed. - pod_namespace (str): - The namespace of the pod where the command is - executed. - next_line_number (int): - Line number from which new logs should be - fetched. - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - execution_id: str = proto.Field( - proto.STRING, - number=2, - ) - pod: str = proto.Field( - proto.STRING, - number=3, - ) - pod_namespace: str = proto.Field( - proto.STRING, - number=4, - ) - next_line_number: int = proto.Field( - proto.INT32, - number=5, - ) - - -class PollAirflowCommandResponse(proto.Message): - r"""Response to PollAirflowCommandRequest. - - Attributes: - output (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse.Line]): - Output from the command execution. It may not - contain the full output and the caller may need - to poll for more lines. - output_end (bool): - Whether the command execution has finished - and there is no more output. - exit_info (google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse.ExitInfo): - The result exit status of the command. - """ - - class Line(proto.Message): - r"""Contains information about a single line from logs. - - Attributes: - line_number (int): - Number of the line. - content (str): - Text content of the log line. - """ - - line_number: int = proto.Field( - proto.INT32, - number=1, - ) - content: str = proto.Field( - proto.STRING, - number=2, - ) - - class ExitInfo(proto.Message): - r"""Information about how a command ended. - - Attributes: - exit_code (int): - The exit code from the command execution. - error (str): - Error message. Empty if there was no error. - """ - - exit_code: int = proto.Field( - proto.INT32, - number=1, - ) - error: str = proto.Field( - proto.STRING, - number=2, - ) - - output: MutableSequence[Line] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Line, - ) - output_end: bool = proto.Field( - proto.BOOL, - number=2, - ) - exit_info: ExitInfo = proto.Field( - proto.MESSAGE, - number=3, - message=ExitInfo, - ) - - -class CreateUserWorkloadsSecretRequest(proto.Message): - r"""Create user workloads Secret request. - - Attributes: - parent (str): - Required. The environment name to create a - Secret for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - user_workloads_secret (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret): - Required. User workloads Secret to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_workloads_secret: 'UserWorkloadsSecret' = proto.Field( - proto.MESSAGE, - number=2, - message='UserWorkloadsSecret', - ) - - -class GetUserWorkloadsSecretRequest(proto.Message): - r"""Get user workloads Secret request. - - Attributes: - name (str): - Required. The resource name of the Secret to - get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListUserWorkloadsSecretsRequest(proto.Message): - r"""List user workloads Secrets request. - - Attributes: - parent (str): - Required. List Secrets in the given - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - page_size (int): - Optional. The maximum number of Secrets to - return. - page_token (str): - Optional. The next_page_token value returned from a previous - List 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 UpdateUserWorkloadsSecretRequest(proto.Message): - r"""Update user workloads Secret request. - - Attributes: - user_workloads_secret (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret): - Optional. User workloads Secret to override. - """ - - user_workloads_secret: 'UserWorkloadsSecret' = proto.Field( - proto.MESSAGE, - number=1, - message='UserWorkloadsSecret', - ) - - -class DeleteUserWorkloadsSecretRequest(proto.Message): - r"""Delete user workloads Secret request. - - Attributes: - name (str): - Required. The Secret to delete, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateUserWorkloadsConfigMapRequest(proto.Message): - r"""Create user workloads ConfigMap request. - - Attributes: - parent (str): - Required. The environment name to create a - ConfigMap for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - user_workloads_config_map (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap): - Required. User workloads ConfigMap to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_workloads_config_map: 'UserWorkloadsConfigMap' = proto.Field( - proto.MESSAGE, - number=2, - message='UserWorkloadsConfigMap', - ) - - -class GetUserWorkloadsConfigMapRequest(proto.Message): - r"""Get user workloads ConfigMap request. - - Attributes: - name (str): - Required. The resource name of the ConfigMap - to get, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListUserWorkloadsConfigMapsRequest(proto.Message): - r"""List user workloads ConfigMaps request. - - Attributes: - parent (str): - Required. List ConfigMaps in the given - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - page_size (int): - Optional. The maximum number of ConfigMaps to - return. - page_token (str): - Optional. The next_page_token value returned from a previous - List 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 UpdateUserWorkloadsConfigMapRequest(proto.Message): - r"""Update user workloads ConfigMap request. - - Attributes: - user_workloads_config_map (google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap): - Optional. User workloads ConfigMap to - override. - """ - - user_workloads_config_map: 'UserWorkloadsConfigMap' = proto.Field( - proto.MESSAGE, - number=1, - message='UserWorkloadsConfigMap', - ) - - -class DeleteUserWorkloadsConfigMapRequest(proto.Message): - r"""Delete user workloads ConfigMap request. - - Attributes: - name (str): - Required. The ConfigMap to delete, in the - form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UserWorkloadsSecret(proto.Message): - r"""User workloads Secret used by Airflow tasks that run with - Kubernetes executor or KubernetesPodOperator. - - Attributes: - name (str): - Identifier. The resource name of the Secret, - in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsSecrets/{userWorkloadsSecretId}". - data (MutableMapping[str, str]): - Optional. The "data" field of Kubernetes - Secret, organized in key-value pairs, which can - contain sensitive values such as a password, a - token, or a key. The values for all keys have to - be base64-encoded strings. For details see: - https://kubernetes.io/docs/concepts/configuration/secret/ - - Example: - - { - "example": "ZXhhbXBsZV92YWx1ZQ==", - "another-example": - "YW5vdGhlcl9leGFtcGxlX3ZhbHVl" } - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - data: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -class ListUserWorkloadsSecretsResponse(proto.Message): - r"""The user workloads Secrets for a given environment. - - Attributes: - user_workloads_secrets (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret]): - The list of Secrets returned by a - ListUserWorkloadsSecretsRequest. - next_page_token (str): - The page token used to query for the next - page if one exists. - """ - - @property - def raw_page(self): - return self - - user_workloads_secrets: MutableSequence['UserWorkloadsSecret'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='UserWorkloadsSecret', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UserWorkloadsConfigMap(proto.Message): - r"""User workloads ConfigMap used by Airflow tasks that run with - Kubernetes executor or KubernetesPodOperator. - - Attributes: - name (str): - Identifier. The resource name of the - ConfigMap, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}/userWorkloadsConfigMaps/{userWorkloadsConfigMapId}". - data (MutableMapping[str, str]): - Optional. The "data" field of Kubernetes ConfigMap, - organized in key-value pairs. For details see: - https://kubernetes.io/docs/concepts/configuration/configmap/ - - Example: - - { "example_key": "example_value", "another_key": - "another_value" } - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - data: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -class ListUserWorkloadsConfigMapsResponse(proto.Message): - r"""The user workloads ConfigMaps for a given environment. - - Attributes: - user_workloads_config_maps (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap]): - The list of ConfigMaps returned by a - ListUserWorkloadsConfigMapsRequest. - next_page_token (str): - The page token used to query for the next - page if one exists. - """ - - @property - def raw_page(self): - return self - - user_workloads_config_maps: MutableSequence['UserWorkloadsConfigMap'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='UserWorkloadsConfigMap', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListWorkloadsRequest(proto.Message): - r"""Request for listing workloads in a Cloud Composer - environment. - - Attributes: - parent (str): - Required. The environment name to get - workloads for, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - page_size (int): - Optional. The maximum number of environments - to return. - page_token (str): - Optional. The next_page_token value returned from a previous - List request, if any. - filter (str): - Optional. The list filter. Currently only supports equality - on the type field. The value of a field specified in the - filter expression must be one ComposerWorkloadType enum - option. It's possible to get multiple types using "OR" - operator, e.g.: "type=SCHEDULER OR type=CELERY_WORKER". If - not specified, all items are returned. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListWorkloadsResponse(proto.Message): - r"""Response to ListWorkloadsRequest. - - Attributes: - workloads (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse.ComposerWorkload]): - The list of environment workloads. - next_page_token (str): - The page token used to query for the next - page if one exists. - """ - class ComposerWorkloadType(proto.Enum): - r"""Supported workload types. - - Values: - COMPOSER_WORKLOAD_TYPE_UNSPECIFIED (0): - Not able to determine the type of the - workload. - CELERY_WORKER (1): - Celery worker. - KUBERNETES_WORKER (2): - Kubernetes worker. - KUBERNETES_OPERATOR_POD (3): - Workload created by Kubernetes Pod Operator. - SCHEDULER (4): - Airflow scheduler. - DAG_PROCESSOR (5): - Airflow Dag processor. - TRIGGERER (6): - Airflow triggerer. - WEB_SERVER (7): - Airflow web server UI. - REDIS (8): - Redis. - """ - COMPOSER_WORKLOAD_TYPE_UNSPECIFIED = 0 - CELERY_WORKER = 1 - KUBERNETES_WORKER = 2 - KUBERNETES_OPERATOR_POD = 3 - SCHEDULER = 4 - DAG_PROCESSOR = 5 - TRIGGERER = 6 - WEB_SERVER = 7 - REDIS = 8 - - class ComposerWorkloadState(proto.Enum): - r"""Workload states. - - Values: - COMPOSER_WORKLOAD_STATE_UNSPECIFIED (0): - Not able to determine the status of the - workload. - PENDING (1): - Workload is in pending state and has not yet - started. - OK (2): - Workload is running fine. - WARNING (3): - Workload is running but there are some - non-critical problems. - ERROR (4): - Workload is not running due to an error. - SUCCEEDED (5): - Workload has finished execution with success. - FAILED (6): - Workload has finished execution with failure. - """ - COMPOSER_WORKLOAD_STATE_UNSPECIFIED = 0 - PENDING = 1 - OK = 2 - WARNING = 3 - ERROR = 4 - SUCCEEDED = 5 - FAILED = 6 - - class ComposerWorkload(proto.Message): - r"""Information about a single workload. - - Attributes: - name (str): - Name of a workload. - type_ (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse.ComposerWorkloadType): - Type of a workload. - status (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse.ComposerWorkloadStatus): - Output only. Status of a workload. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: 'ListWorkloadsResponse.ComposerWorkloadType' = proto.Field( - proto.ENUM, - number=2, - enum='ListWorkloadsResponse.ComposerWorkloadType', - ) - status: 'ListWorkloadsResponse.ComposerWorkloadStatus' = proto.Field( - proto.MESSAGE, - number=3, - message='ListWorkloadsResponse.ComposerWorkloadStatus', - ) - - class ComposerWorkloadStatus(proto.Message): - r"""Workload status. - - Attributes: - state (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse.ComposerWorkloadState): - Output only. Workload state. - status_message (str): - Output only. Text to provide more descriptive - status. - detailed_status_message (str): - Output only. Detailed message of the status. - """ - - state: 'ListWorkloadsResponse.ComposerWorkloadState' = proto.Field( - proto.ENUM, - number=1, - enum='ListWorkloadsResponse.ComposerWorkloadState', - ) - status_message: str = proto.Field( - proto.STRING, - number=2, - ) - detailed_status_message: str = proto.Field( - proto.STRING, - number=3, - ) - - @property - def raw_page(self): - return self - - workloads: MutableSequence[ComposerWorkload] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ComposerWorkload, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SaveSnapshotRequest(proto.Message): - r"""Request to create a snapshot of a Cloud Composer environment. - - Attributes: - environment (str): - The resource name of the source environment - in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - snapshot_location (str): - Location in a Cloud Storage where the - snapshot is going to be stored, e.g.: - "gs://my-bucket/snapshots". - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - snapshot_location: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SaveSnapshotResponse(proto.Message): - r"""Response to SaveSnapshotRequest. - - Attributes: - snapshot_path (str): - The fully-resolved Cloud Storage path of the created - snapshot, e.g.: - "gs://my-bucket/snapshots/project_location_environment_timestamp". - This field is populated only if the snapshot creation was - successful. - """ - - snapshot_path: str = proto.Field( - proto.STRING, - number=1, - ) - - -class LoadSnapshotRequest(proto.Message): - r"""Request to load a snapshot into a Cloud Composer environment. - - Attributes: - environment (str): - The resource name of the target environment - in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - snapshot_path (str): - A Cloud Storage path to a snapshot to load, e.g.: - "gs://my-bucket/snapshots/project_location_environment_timestamp". - skip_pypi_packages_installation (bool): - Whether or not to skip installing Pypi - packages when loading the environment's state. - skip_environment_variables_setting (bool): - Whether or not to skip setting environment - variables when loading the environment's state. - skip_airflow_overrides_setting (bool): - Whether or not to skip setting Airflow - overrides when loading the environment's state. - skip_gcs_data_copying (bool): - Whether or not to skip copying Cloud Storage - data when loading the environment's state. - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - snapshot_path: str = proto.Field( - proto.STRING, - number=2, - ) - skip_pypi_packages_installation: bool = proto.Field( - proto.BOOL, - number=3, - ) - skip_environment_variables_setting: bool = proto.Field( - proto.BOOL, - number=4, - ) - skip_airflow_overrides_setting: bool = proto.Field( - proto.BOOL, - number=5, - ) - skip_gcs_data_copying: bool = proto.Field( - proto.BOOL, - number=6, - ) - - -class LoadSnapshotResponse(proto.Message): - r"""Response to LoadSnapshotRequest. - """ - - -class DatabaseFailoverRequest(proto.Message): - r"""Request to trigger database failover (only for highly - resilient environments). - - Attributes: - environment (str): - Target environment: - - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DatabaseFailoverResponse(proto.Message): - r"""Response for DatabaseFailoverRequest. - """ - - -class FetchDatabasePropertiesRequest(proto.Message): - r"""Request to fetch properties of environment's database. - - Attributes: - environment (str): - Required. The resource name of the - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - - -class FetchDatabasePropertiesResponse(proto.Message): - r"""Response for FetchDatabasePropertiesRequest. - - Attributes: - primary_gce_zone (str): - The Compute Engine zone that the instance is - currently serving from. - secondary_gce_zone (str): - The Compute Engine zone that the failover - instance is currently serving from for a - regional Cloud SQL instance. - is_failover_replica_available (bool): - The availability status of the failover - replica. A false status indicates that the - failover replica is out of sync. The primary - instance can only fail over to the failover - replica when the status is true. - """ - - primary_gce_zone: str = proto.Field( - proto.STRING, - number=1, - ) - secondary_gce_zone: str = proto.Field( - proto.STRING, - number=2, - ) - is_failover_replica_available: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class EnvironmentConfig(proto.Message): - r"""Configuration information for an environment. - - Attributes: - gke_cluster (str): - Output only. The Kubernetes Engine cluster - used to run this environment. - dag_gcs_prefix (str): - Output only. The Cloud Storage prefix of the - DAGs for this environment. Although Cloud - Storage objects reside in a flat namespace, a - hierarchical file tree can be simulated using - "/"-delimited object name prefixes. DAG objects - for this environment reside in a simulated - directory with the given prefix. - node_count (int): - The number of nodes in the Kubernetes Engine cluster that - will be used to run this environment. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - software_config (google.cloud.orchestration.airflow.service_v1beta1.types.SoftwareConfig): - Optional. The configuration settings for - software inside the environment. - node_config (google.cloud.orchestration.airflow.service_v1beta1.types.NodeConfig): - Optional. The configuration used for the - Kubernetes Engine cluster. - private_environment_config (google.cloud.orchestration.airflow.service_v1beta1.types.PrivateEnvironmentConfig): - Optional. The configuration used for the - Private IP Cloud Composer environment. - web_server_network_access_control (google.cloud.orchestration.airflow.service_v1beta1.types.WebServerNetworkAccessControl): - Optional. The network-level access control - policy for the Airflow web server. If - unspecified, no network-level access - restrictions will be applied. - database_config (google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseConfig): - Optional. The configuration settings for - Cloud SQL instance used internally by Apache - Airflow software. - web_server_config (google.cloud.orchestration.airflow.service_v1beta1.types.WebServerConfig): - Optional. The configuration settings for the Airflow web - server App Engine instance. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - airflow_uri (str): - Output only. The URI of the Apache Airflow Web UI hosted - within this environment (see `Airflow web - interface `__). - airflow_byoid_uri (str): - Output only. The 'bring your own identity' variant of the - URI of the Apache Airflow Web UI hosted within this - environment, to be accessed with external identities using - workforce identity federation (see `Access environments with - workforce identity - federation `__). - encryption_config (google.cloud.orchestration.airflow.service_v1beta1.types.EncryptionConfig): - Optional. The encryption options for the - Cloud Composer environment and its dependencies. - Cannot be updated. - maintenance_window (google.cloud.orchestration.airflow.service_v1beta1.types.MaintenanceWindow): - Optional. The maintenance window is the - period when Cloud Composer components may - undergo maintenance. It is defined so that - maintenance is not executed during peak hours or - critical time periods. - - The system will not be under maintenance for - every occurrence of this window, but when - maintenance is planned, it will be scheduled - during the window. - - The maintenance window period must encompass at - least 12 hours per week. This may be split into - multiple chunks, each with a size of at least 4 - hours. - - If this value is omitted, the default value for - maintenance window is applied. By default, - maintenance windows are from 00:00:00 to - 04:00:00 (GMT) on Friday, Saturday, and Sunday - every week. - workloads_config (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig): - Optional. The workloads configuration settings for the GKE - cluster associated with the Cloud Composer environment. The - GKE cluster runs Airflow scheduler, web server and workers - workloads. - - This field is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - environment_size (google.cloud.orchestration.airflow.service_v1beta1.types.EnvironmentConfig.EnvironmentSize): - Optional. The size of the Cloud Composer environment. - - This field is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - master_authorized_networks_config (google.cloud.orchestration.airflow.service_v1beta1.types.MasterAuthorizedNetworksConfig): - Optional. The configuration options for GKE - cluster master authorized networks. By default - master authorized networks feature is: - - - in case of private environment: enabled with - no external networks allowlisted. - - in case of public environment: disabled. - recovery_config (google.cloud.orchestration.airflow.service_v1beta1.types.RecoveryConfig): - Optional. The Recovery settings configuration of an - environment. - - This field is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - data_retention_config (google.cloud.orchestration.airflow.service_v1beta1.types.DataRetentionConfig): - Optional. The configuration setting for - Airflow database data retention mechanism. - resilience_mode (google.cloud.orchestration.airflow.service_v1beta1.types.EnvironmentConfig.ResilienceMode): - Optional. Resilience mode of the Cloud Composer Environment. - - This field is supported for Cloud Composer environments in - versions composer-2.2.0-airflow-\ *.*.\* and newer. - """ - class EnvironmentSize(proto.Enum): - r"""The size of the Cloud Composer environment. - - Values: - ENVIRONMENT_SIZE_UNSPECIFIED (0): - The size of the environment is unspecified. - ENVIRONMENT_SIZE_SMALL (1): - The environment size is small. - ENVIRONMENT_SIZE_MEDIUM (2): - The environment size is medium. - ENVIRONMENT_SIZE_LARGE (3): - The environment size is large. - """ - ENVIRONMENT_SIZE_UNSPECIFIED = 0 - ENVIRONMENT_SIZE_SMALL = 1 - ENVIRONMENT_SIZE_MEDIUM = 2 - ENVIRONMENT_SIZE_LARGE = 3 - - class ResilienceMode(proto.Enum): - r"""Resilience mode of the Cloud Composer Environment. - - Values: - RESILIENCE_MODE_UNSPECIFIED (0): - Default mode doesn't change environment - parameters. - HIGH_RESILIENCE (1): - Enabled High Resilience mode, including Cloud - SQL HA. - """ - RESILIENCE_MODE_UNSPECIFIED = 0 - HIGH_RESILIENCE = 1 - - gke_cluster: str = proto.Field( - proto.STRING, - number=1, - ) - dag_gcs_prefix: str = proto.Field( - proto.STRING, - number=2, - ) - node_count: int = proto.Field( - proto.INT32, - number=3, - ) - software_config: 'SoftwareConfig' = proto.Field( - proto.MESSAGE, - number=4, - message='SoftwareConfig', - ) - node_config: 'NodeConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='NodeConfig', - ) - private_environment_config: 'PrivateEnvironmentConfig' = proto.Field( - proto.MESSAGE, - number=7, - message='PrivateEnvironmentConfig', - ) - web_server_network_access_control: 'WebServerNetworkAccessControl' = proto.Field( - proto.MESSAGE, - number=9, - message='WebServerNetworkAccessControl', - ) - database_config: 'DatabaseConfig' = proto.Field( - proto.MESSAGE, - number=10, - message='DatabaseConfig', - ) - web_server_config: 'WebServerConfig' = proto.Field( - proto.MESSAGE, - number=11, - message='WebServerConfig', - ) - airflow_uri: str = proto.Field( - proto.STRING, - number=6, - ) - airflow_byoid_uri: str = proto.Field( - proto.STRING, - number=21, - ) - encryption_config: 'EncryptionConfig' = proto.Field( - proto.MESSAGE, - number=12, - message='EncryptionConfig', - ) - maintenance_window: 'MaintenanceWindow' = proto.Field( - proto.MESSAGE, - number=13, - message='MaintenanceWindow', - ) - workloads_config: 'WorkloadsConfig' = proto.Field( - proto.MESSAGE, - number=15, - message='WorkloadsConfig', - ) - environment_size: EnvironmentSize = proto.Field( - proto.ENUM, - number=16, - enum=EnvironmentSize, - ) - master_authorized_networks_config: 'MasterAuthorizedNetworksConfig' = proto.Field( - proto.MESSAGE, - number=17, - message='MasterAuthorizedNetworksConfig', - ) - recovery_config: 'RecoveryConfig' = proto.Field( - proto.MESSAGE, - number=18, - message='RecoveryConfig', - ) - data_retention_config: 'DataRetentionConfig' = proto.Field( - proto.MESSAGE, - number=19, - message='DataRetentionConfig', - ) - resilience_mode: ResilienceMode = proto.Field( - proto.ENUM, - number=20, - enum=ResilienceMode, - ) - - -class WebServerNetworkAccessControl(proto.Message): - r"""Network-level access control policy for the Airflow web - server. - - Attributes: - allowed_ip_ranges (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.WebServerNetworkAccessControl.AllowedIpRange]): - A collection of allowed IP ranges with - descriptions. - """ - - class AllowedIpRange(proto.Message): - r"""Allowed IP range with user-provided description. - - Attributes: - value (str): - IP address or range, defined using CIDR notation, of - requests that this rule applies to. Examples: - ``192.168.1.1`` or ``192.168.0.0/16`` or ``2001:db8::/32`` - or ``2001:0db8:0000:0042:0000:8a2e:0370:7334``. - - IP range prefixes should be properly truncated. For example, - ``1.2.3.4/24`` should be truncated to ``1.2.3.0/24``. - Similarly, for IPv6, ``2001:db8::1/32`` should be truncated - to ``2001:db8::/32``. - description (str): - Optional. User-provided description. It must - contain at most 300 characters. - """ - - value: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - - allowed_ip_ranges: MutableSequence[AllowedIpRange] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=AllowedIpRange, - ) - - -class SoftwareConfig(proto.Message): - r"""Specifies the selection and configuration of software inside - the environment. - - Attributes: - image_version (str): - Optional. The version of the software running in the - environment. This encapsulates both the version of Cloud - Composer functionality and the version of Apache Airflow. It - must match the regular expression - ``composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)``. - When used as input, the server also checks if the provided - version is supported and denies the request for an - unsupported version. - - The Cloud Composer portion of the image version is a full - `semantic version `__, or an alias in - the form of major version number or ``latest``. When an - alias is provided, the server replaces it with the current - Cloud Composer version that satisfies the alias. - - The Apache Airflow portion of the image version is a full - semantic version that points to one of the supported Apache - Airflow versions, or an alias in the form of only major or - major.minor versions specified. When an alias is provided, - the server replaces it with the latest Apache Airflow - version that satisfies the alias and is supported in the - given Cloud Composer version. - - In all cases, the resolved image version is stored in the - same field. - - See also `version - list `__ - and `versioning - overview `__. - airflow_config_overrides (MutableMapping[str, str]): - Optional. Apache Airflow configuration properties to - override. - - Property keys contain the section and property names, - separated by a hyphen, for example - "core-dags_are_paused_at_creation". Section names must not - contain hyphens ("-"), opening square brackets ("["), or - closing square brackets ("]"). The property name must not be - empty and must not contain an equals sign ("=") or semicolon - (";"). Section and property names must not contain a period - ("."). Apache Airflow configuration property names must be - written in - `snake_case `__. - Property values can contain any character, and can be - written in any lower/upper case format. - - Certain Apache Airflow configuration property values are - `blocked `__, - and cannot be overridden. - pypi_packages (MutableMapping[str, str]): - Optional. Custom Python Package Index (PyPI) packages to be - installed in the environment. - - Keys refer to the lowercase package name such as "numpy" and - values are the lowercase extras and version specifier such - as "==1.12.0", "[devel,gcp_api]", or "[devel]>=1.8.2, - <1.9.2". To specify a package without pinning it to a - version specifier, use the empty string as the value. - env_variables (MutableMapping[str, str]): - Optional. Additional environment variables to provide to the - Apache Airflow scheduler, worker, and webserver processes. - - Environment variable names must match the regular expression - ``[a-zA-Z_][a-zA-Z0-9_]*``. They cannot specify Apache - Airflow software configuration overrides (they cannot match - the regular expression ``AIRFLOW__[A-Z0-9_]+__[A-Z0-9_]+``), - and they cannot match any of the following reserved names: - - - ``AIRFLOW_HOME`` - - ``C_FORCE_ROOT`` - - ``CONTAINER_NAME`` - - ``DAGS_FOLDER`` - - ``GCP_PROJECT`` - - ``GCS_BUCKET`` - - ``GKE_CLUSTER_NAME`` - - ``SQL_DATABASE`` - - ``SQL_INSTANCE`` - - ``SQL_PASSWORD`` - - ``SQL_PROJECT`` - - ``SQL_REGION`` - - ``SQL_USER`` - python_version (str): - Optional. The major version of Python used to run the Apache - Airflow scheduler, worker, and webserver processes. - - Can be set to '2' or '3'. If not specified, the default is - '3'. Cannot be updated. - - This field is only supported for Cloud Composer environments - in versions composer-1.\ *.*-airflow-*.*.*. Environments in - newer versions always use Python major version 3. - scheduler_count (int): - Optional. The number of schedulers for Airflow. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-2.*.*. - cloud_data_lineage_integration (google.cloud.orchestration.airflow.service_v1beta1.types.CloudDataLineageIntegration): - Optional. The configuration for Cloud Data - Lineage integration. - web_server_plugins_mode (google.cloud.orchestration.airflow.service_v1beta1.types.SoftwareConfig.WebServerPluginsMode): - Optional. Whether or not the web server uses custom plugins. - If unspecified, the field defaults to ``PLUGINS_ENABLED``. - - This field is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - """ - class WebServerPluginsMode(proto.Enum): - r"""Web server plugins mode of the Cloud Composer environment. - - Values: - WEB_SERVER_PLUGINS_MODE_UNSPECIFIED (0): - Default mode. - PLUGINS_DISABLED (1): - Web server plugins are not supported. - PLUGINS_ENABLED (2): - Web server plugins are supported. - """ - WEB_SERVER_PLUGINS_MODE_UNSPECIFIED = 0 - PLUGINS_DISABLED = 1 - PLUGINS_ENABLED = 2 - - image_version: str = proto.Field( - proto.STRING, - number=1, - ) - airflow_config_overrides: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - pypi_packages: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - env_variables: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - python_version: str = proto.Field( - proto.STRING, - number=6, - ) - scheduler_count: int = proto.Field( - proto.INT32, - number=7, - ) - cloud_data_lineage_integration: 'CloudDataLineageIntegration' = proto.Field( - proto.MESSAGE, - number=8, - message='CloudDataLineageIntegration', - ) - web_server_plugins_mode: WebServerPluginsMode = proto.Field( - proto.ENUM, - number=10, - enum=WebServerPluginsMode, - ) - - -class IPAllocationPolicy(proto.Message): - r"""Configuration for controlling how IPs are allocated in the - GKE cluster. - - Attributes: - use_ip_aliases (bool): - Optional. Whether or not to enable Alias IPs in the GKE - cluster. If ``true``, a VPC-native cluster is created. - - This field is only supported for Cloud Composer environments - in versions composer-1.\ *.*-airflow-*.*.*. Environments in - newer versions always use VPC-native GKE clusters. - cluster_secondary_range_name (str): - Optional. The name of the cluster's secondary range used to - allocate IP addresses to pods. Specify either - ``cluster_secondary_range_name`` or - ``cluster_ipv4_cidr_block`` but not both. - - For Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*, this field is applicable - only when ``use_ip_aliases`` is true. - services_secondary_range_name (str): - Optional. The name of the services' secondary range used to - allocate IP addresses to the cluster. Specify either - ``services_secondary_range_name`` or - ``services_ipv4_cidr_block`` but not both. - - For Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*, this field is applicable - only when ``use_ip_aliases`` is true. - cluster_ipv4_cidr_block (str): - Optional. The IP address range used to allocate IP addresses - to pods in the cluster. - - For Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*, this field is applicable - only when ``use_ip_aliases`` is true. - - Set to blank to have GKE choose a range with the default - size. - - Set to /netmask (e.g. ``/14``) to have GKE choose a range - with a specific netmask. - - Set to a - `CIDR `__ - notation (e.g. ``10.96.0.0/14``) from the RFC-1918 private - networks (e.g. ``10.0.0.0/8``, ``172.16.0.0/12``, - ``192.168.0.0/16``) to pick a specific range to use. Specify - ``cluster_secondary_range_name`` or - ``cluster_ipv4_cidr_block`` but not both. - services_ipv4_cidr_block (str): - Optional. The IP address range of the services IP addresses - in this cluster. - - For Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*, this field is applicable - only when ``use_ip_aliases`` is true. - - Set to blank to have GKE choose a range with the default - size. - - Set to /netmask (e.g. ``/14``) to have GKE choose a range - with a specific netmask. - - Set to a - `CIDR `__ - notation (e.g. ``10.96.0.0/14``) from the RFC-1918 private - networks (e.g. ``10.0.0.0/8``, ``172.16.0.0/12``, - ``192.168.0.0/16``) to pick a specific range to use. Specify - ``services_secondary_range_name`` or - ``services_ipv4_cidr_block`` but not both. - """ - - use_ip_aliases: bool = proto.Field( - proto.BOOL, - number=1, - ) - cluster_secondary_range_name: str = proto.Field( - proto.STRING, - number=2, - ) - services_secondary_range_name: str = proto.Field( - proto.STRING, - number=3, - ) - cluster_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=4, - ) - services_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=5, - ) - - -class NodeConfig(proto.Message): - r"""The configuration information for the Kubernetes Engine nodes - running the Apache Airflow software. - - Attributes: - location (str): - Optional. The Compute Engine - `zone `__ in which to deploy - the VMs used to run the Apache Airflow software, specified - as a `relative resource - name `__. - For example: "projects/{projectId}/zones/{zoneId}". - - This ``location`` must belong to the enclosing environment's - project and location. If both this field and - ``nodeConfig.machineType`` are specified, - ``nodeConfig.machineType`` must belong to this ``location``; - if both are unspecified, the service will pick a zone in the - Compute Engine region corresponding to the Cloud Composer - location, and propagate that choice to both fields. If only - one field (``location`` or ``nodeConfig.machineType``) is - specified, the location information from the specified field - will be propagated to the unspecified field. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - machine_type (str): - Optional. The Compute Engine `machine - type `__ used for cluster - instances, specified as a `relative resource - name `__. - For example: - "projects/{projectId}/zones/{zoneId}/machineTypes/{machineTypeId}". - - The ``machineType`` must belong to the enclosing - environment's project and location. If both this field and - ``nodeConfig.location`` are specified, this ``machineType`` - must belong to the ``nodeConfig.location``; if both are - unspecified, the service will pick a zone in the Compute - Engine region corresponding to the Cloud Composer location, - and propagate that choice to both fields. If exactly one of - this field and ``nodeConfig.location`` is specified, the - location information from the specified field will be - propagated to the unspecified field. - - The ``machineTypeId`` must not be a `shared-core machine - type `__. - - If this field is unspecified, the ``machineTypeId`` defaults - to "n1-standard-1". - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - network (str): - Optional. The Compute Engine network to be used for machine - communications, specified as a `relative resource - name `__. - For example: - "projects/{projectId}/global/networks/{networkId}". - - If unspecified, the default network in the environment's - project is used. If a `Custom Subnet - Network `__ is - provided, ``nodeConfig.subnetwork`` must also be provided. - For `Shared VPC `__ subnetwork - requirements, see ``nodeConfig.subnetwork``. - subnetwork (str): - Optional. The Compute Engine subnetwork to be used for - machine communications, specified as a `relative resource - name `__. - For example: - "projects/{projectId}/regions/{regionId}/subnetworks/{subnetworkId}" - - If a subnetwork is provided, ``nodeConfig.network`` must - also be provided, and the subnetwork must belong to the - enclosing environment's project and location. - disk_size_gb (int): - Optional. The disk size in GB used for node VMs. Minimum - size is 30GB. If unspecified, defaults to 100GB. Cannot be - updated. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - oauth_scopes (MutableSequence[str]): - Optional. The set of Google API scopes to be made available - on all node VMs. If ``oauth_scopes`` is empty, defaults to - ["https://www.googleapis.com/auth/cloud-platform"]. Cannot - be updated. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - service_account (str): - Optional. The Google Cloud Platform Service - Account to be used by the workloads. If a - service account is not specified, the "default" - Compute Engine service account is used. Cannot - be updated. - tags (MutableSequence[str]): - Optional. The list of instance tags applied to all node VMs. - Tags are used to identify valid sources or targets for - network firewalls. Each tag within the list must comply with - `RFC1035 `__. Cannot - be updated. - ip_allocation_policy (google.cloud.orchestration.airflow.service_v1beta1.types.IPAllocationPolicy): - Optional. The IPAllocationPolicy fields for - the GKE cluster. - max_pods_per_node (int): - Optional. The maximum number of pods per node in the Cloud - Composer GKE cluster. The value must be between 8 and 110 - and it can be set only if the environment is VPC-native. The - default value is 32. Values of this field will be propagated - both to the ``default-pool`` node pool of the newly created - GKE cluster, and to the default "Maximum Pods per Node" - value which is used for newly created node pools if their - value is not explicitly set during node pool creation. For - more information, see [Optimizing IP address allocation] - (https://cloud.google.com/kubernetes-engine/docs/how-to/flexible-pod-cidr). - Cannot be updated. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - enable_ip_masq_agent (bool): - Optional. Deploys 'ip-masq-agent' daemon set - in the GKE cluster and defines - nonMasqueradeCIDRs equals to pod IP range so IP - masquerading is used for all destination - addresses, except between pods traffic. - - See: - - https://cloud.google.com/kubernetes-engine/docs/how-to/ip-masquerade-agent - composer_network_attachment (str): - Optional. Network Attachment that Cloud Composer environment - is connected to, which provides connectivity with a user's - VPC network. Takes precedence over network and subnetwork - settings. If not provided, but network and subnetwork are - defined during environment, it will be provisioned. If not - provided and network and subnetwork are also empty, then - connectivity to user's VPC network is disabled. Network - attachment must be provided in format - projects/{project}/regions/{region}/networkAttachments/{networkAttachment}. - - This field is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - composer_internal_ipv4_cidr_block (str): - Optional. The IP range in CIDR notation to use internally by - Cloud Composer. IP addresses are not reserved - and the same - range can be used by multiple Cloud Composer environments. - In case of overlap, IPs from this range will not be - accessible in the user's VPC network. Cannot be updated. If - not specified, the default value of '100.64.128.0/20' is - used. - - This field is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - """ - - location: str = proto.Field( - proto.STRING, - number=1, - ) - machine_type: str = proto.Field( - proto.STRING, - number=2, - ) - network: str = proto.Field( - proto.STRING, - number=3, - ) - subnetwork: str = proto.Field( - proto.STRING, - number=4, - ) - disk_size_gb: int = proto.Field( - proto.INT32, - number=5, - ) - oauth_scopes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - service_account: str = proto.Field( - proto.STRING, - number=7, - ) - tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - ip_allocation_policy: 'IPAllocationPolicy' = proto.Field( - proto.MESSAGE, - number=9, - message='IPAllocationPolicy', - ) - max_pods_per_node: int = proto.Field( - proto.INT32, - number=10, - ) - enable_ip_masq_agent: bool = proto.Field( - proto.BOOL, - number=11, - ) - composer_network_attachment: str = proto.Field( - proto.STRING, - number=12, - ) - composer_internal_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=13, - ) - - -class PrivateClusterConfig(proto.Message): - r"""Configuration options for the private GKE cluster in a Cloud - Composer environment. - - Attributes: - enable_private_endpoint (bool): - Optional. If ``true``, access to the public endpoint of the - GKE cluster is denied. - master_ipv4_cidr_block (str): - Optional. The CIDR block from which IPv4 - range for GKE master will be reserved. If left - blank, the default value of '172.16.0.0/23' is - used. - master_ipv4_reserved_range (str): - Output only. The IP range in CIDR notation to - use for the hosted master network. This range is - used for assigning internal IP addresses to the - cluster master or set of masters and to the - internal load balancer virtual IP. This range - must not overlap with any other ranges in use - within the cluster's network. - """ - - enable_private_endpoint: bool = proto.Field( - proto.BOOL, - number=1, - ) - master_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=2, - ) - master_ipv4_reserved_range: str = proto.Field( - proto.STRING, - number=3, - ) - - -class NetworkingConfig(proto.Message): - r"""Configuration options for networking connections in the - Composer 2 environment. - - Attributes: - connection_type (google.cloud.orchestration.airflow.service_v1beta1.types.NetworkingConfig.ConnectionType): - Optional. Indicates the user requested - specifc connection type between Tenant and - Customer projects. You cannot set networking - connection type in public IP environment. - """ - class ConnectionType(proto.Enum): - r"""Represents connection type between Composer environment in - Customer Project and the corresponding Tenant project, from a - predefined list of available connection modes. - - Values: - CONNECTION_TYPE_UNSPECIFIED (0): - No specific connection type was requested, so - the environment uses the default value - corresponding to the rest of its configuration. - VPC_PEERING (1): - Requests the use of VPC peerings for - connecting the Customer and Tenant projects. - PRIVATE_SERVICE_CONNECT (2): - Requests the use of Private Service Connect - for connecting the Customer and Tenant projects. - """ - CONNECTION_TYPE_UNSPECIFIED = 0 - VPC_PEERING = 1 - PRIVATE_SERVICE_CONNECT = 2 - - connection_type: ConnectionType = proto.Field( - proto.ENUM, - number=1, - enum=ConnectionType, - ) - - -class PrivateEnvironmentConfig(proto.Message): - r"""The configuration information for configuring a Private IP - Cloud Composer environment. - - Attributes: - enable_private_environment (bool): - Optional. If ``true``, a Private IP Cloud Composer - environment is created. If this field is set to true, - ``IPAllocationPolicy.use_ip_aliases`` must be set to true - for Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - enable_private_builds_only (bool): - Optional. If ``true``, builds performed during operations - that install Python packages have only private connectivity - to Google services (including Artifact Registry) and VPC - network (if either ``NodeConfig.network`` and - ``NodeConfig.subnetwork`` fields or - ``NodeConfig.composer_network_attachment`` field are - specified). If ``false``, the builds also have access to the - internet. - - This field is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - private_cluster_config (google.cloud.orchestration.airflow.service_v1beta1.types.PrivateClusterConfig): - Optional. Configuration for the private GKE - cluster for a Private IP Cloud Composer - environment. - web_server_ipv4_cidr_block (str): - Optional. The CIDR block from which IP range for web server - will be reserved. Needs to be disjoint from - private_cluster_config.master_ipv4_cidr_block and - cloud_sql_ipv4_cidr_block. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - cloud_sql_ipv4_cidr_block (str): - Optional. The CIDR block from which IP range in tenant - project will be reserved for Cloud SQL. Needs to be disjoint - from web_server_ipv4_cidr_block - web_server_ipv4_reserved_range (str): - Output only. The IP range reserved for the tenant project's - App Engine VMs. - - This field is supported for Cloud Composer environments in - versions composer-1.\ *.*-airflow-*.*.*. - cloud_composer_network_ipv4_cidr_block (str): - Optional. The CIDR block from which IP range for Cloud - Composer Network in tenant project will be reserved. Needs - to be disjoint from - private_cluster_config.master_ipv4_cidr_block and - cloud_sql_ipv4_cidr_block. - - This field is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - cloud_composer_network_ipv4_reserved_range (str): - Output only. The IP range reserved for the tenant project's - Cloud Composer network. - - This field is supported for Cloud Composer environments in - versions composer-2.\ *.*-airflow-*.*.\* and newer. - enable_privately_used_public_ips (bool): - Optional. When enabled, IPs from public (non-RFC1918) ranges - can be used for - ``IPAllocationPolicy.cluster_ipv4_cidr_block`` and - ``IPAllocationPolicy.service_ipv4_cidr_block``. - cloud_composer_connection_subnetwork (str): - Optional. When specified, the environment - will use Private Service Connect instead of VPC - peerings to connect to Cloud SQL in the Tenant - Project, and the PSC endpoint in the Customer - Project will use an IP address from this - subnetwork. - networking_config (google.cloud.orchestration.airflow.service_v1beta1.types.NetworkingConfig): - Optional. Configuration for the network - connections configuration in the environment. - """ - - enable_private_environment: bool = proto.Field( - proto.BOOL, - number=1, - ) - enable_private_builds_only: bool = proto.Field( - proto.BOOL, - number=11, - ) - private_cluster_config: 'PrivateClusterConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='PrivateClusterConfig', - ) - web_server_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=3, - ) - cloud_sql_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=4, - ) - web_server_ipv4_reserved_range: str = proto.Field( - proto.STRING, - number=5, - ) - cloud_composer_network_ipv4_cidr_block: str = proto.Field( - proto.STRING, - number=7, - ) - cloud_composer_network_ipv4_reserved_range: str = proto.Field( - proto.STRING, - number=8, - ) - enable_privately_used_public_ips: bool = proto.Field( - proto.BOOL, - number=6, - ) - cloud_composer_connection_subnetwork: str = proto.Field( - proto.STRING, - number=9, - ) - networking_config: 'NetworkingConfig' = proto.Field( - proto.MESSAGE, - number=10, - message='NetworkingConfig', - ) - - -class DatabaseConfig(proto.Message): - r"""The configuration of Cloud SQL instance that is used by the - Apache Airflow software. - - Attributes: - machine_type (str): - Optional. Cloud SQL machine type used by Airflow database. - It has to be one of: db-n1-standard-2, db-n1-standard-4, - db-n1-standard-8 or db-n1-standard-16. If not specified, - db-n1-standard-2 will be used. Supported for Cloud Composer - environments in versions composer-1.\ *.*-airflow-*.*.*. - zone (str): - Optional. The Compute Engine zone where the Airflow database - is created. If zone is provided, it must be in the region - selected for the environment. If zone is not provided, a - zone is automatically selected. The zone can only be set - during environment creation. Supported for Cloud Composer - environments in versions composer-2.\ *.*-airflow-*.*.*. - """ - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - zone: str = proto.Field( - proto.STRING, - number=2, - ) - - -class WebServerConfig(proto.Message): - r"""The configuration settings for the Airflow web server App Engine - instance. Supported for Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - Attributes: - machine_type (str): - Optional. Machine type on which Airflow web - server is running. It has to be one of: - composer-n1-webserver-2, composer-n1-webserver-4 - or composer-n1-webserver-8. - If not specified, composer-n1-webserver-2 will - be used. Value custom is returned only in - response, if Airflow web server parameters were - manually changed to a non-standard values. - """ - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - - -class EncryptionConfig(proto.Message): - r"""The encryption options for the Cloud Composer environment and its - dependencies. Supported for Cloud Composer environments in versions - composer-1.\ *.*-airflow-*.*.*. - - Attributes: - kms_key_name (str): - Optional. Customer-managed Encryption Key - available through Google's Key Management - Service. Cannot be updated. If not specified, - Google-managed key will be used. - """ - - kms_key_name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class MaintenanceWindow(proto.Message): - r"""The configuration settings for Cloud Composer maintenance window. - The following example: - - :: - - { - "startTime":"2019-08-01T01:00:00Z" - "endTime":"2019-08-01T07:00:00Z" - "recurrence":"FREQ=WEEKLY;BYDAY=TU,WE" - } - - would define a maintenance window between 01 and 07 hours UTC during - each Tuesday and Wednesday. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Start time of the first recurrence - of the maintenance window. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Required. Maintenance window end time. It is used only to - calculate the duration of the maintenance window. The value - for end_time must be in the future, relative to - ``start_time``. - recurrence (str): - Required. Maintenance window recurrence. Format is a subset - of `RFC-5545 `__ - ``RRULE``. The only allowed values for ``FREQ`` field are - ``FREQ=DAILY`` and ``FREQ=WEEKLY;BYDAY=...`` Example values: - ``FREQ=WEEKLY;BYDAY=TU,WE``, ``FREQ=DAILY``. - """ - - start_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, - ) - recurrence: str = proto.Field( - proto.STRING, - number=3, - ) - - -class WorkloadsConfig(proto.Message): - r"""The Kubernetes workloads configuration for GKE cluster associated - with the Cloud Composer environment. Supported for Cloud Composer - environments in versions composer-2.\ *.*-airflow-*.*.\* and newer. - - Attributes: - scheduler (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig.SchedulerResource): - Optional. Resources used by Airflow - schedulers. - web_server (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig.WebServerResource): - Optional. Resources used by Airflow web - server. - worker (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig.WorkerResource): - Optional. Resources used by Airflow workers. - triggerer (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig.TriggererResource): - Optional. Resources used by Airflow - triggerers. - dag_processor (google.cloud.orchestration.airflow.service_v1beta1.types.WorkloadsConfig.DagProcessorResource): - Optional. Resources used by Airflow DAG processors. - - This field is supported for Cloud Composer environments in - versions composer-3-airflow-\ *.*.\ *-build.* and newer. - """ - - class SchedulerResource(proto.Message): - r"""Configuration for resources used by Airflow schedulers. - - Attributes: - cpu (float): - Optional. CPU request and limit for a single - Airflow scheduler replica. - memory_gb (float): - Optional. Memory (GB) request and limit for a - single Airflow scheduler replica. - storage_gb (float): - Optional. Storage (GB) request and limit for - a single Airflow scheduler replica. - count (int): - Optional. The number of schedulers. - """ - - cpu: float = proto.Field( - proto.FLOAT, - number=1, - ) - memory_gb: float = proto.Field( - proto.FLOAT, - number=2, - ) - storage_gb: float = proto.Field( - proto.FLOAT, - number=3, - ) - count: int = proto.Field( - proto.INT32, - number=4, - ) - - class WebServerResource(proto.Message): - r"""Configuration for resources used by Airflow web server. - - Attributes: - cpu (float): - Optional. CPU request and limit for Airflow - web server. - memory_gb (float): - Optional. Memory (GB) request and limit for - Airflow web server. - storage_gb (float): - Optional. Storage (GB) request and limit for - Airflow web server. - """ - - cpu: float = proto.Field( - proto.FLOAT, - number=1, - ) - memory_gb: float = proto.Field( - proto.FLOAT, - number=2, - ) - storage_gb: float = proto.Field( - proto.FLOAT, - number=3, - ) - - class WorkerResource(proto.Message): - r"""Configuration for resources used by Airflow workers. - - Attributes: - cpu (float): - Optional. CPU request and limit for a single - Airflow worker replica. - memory_gb (float): - Optional. Memory (GB) request and limit for a - single Airflow worker replica. - storage_gb (float): - Optional. Storage (GB) request and limit for - a single Airflow worker replica. - min_count (int): - Optional. Minimum number of workers for - autoscaling. - max_count (int): - Optional. Maximum number of workers for - autoscaling. - """ - - cpu: float = proto.Field( - proto.FLOAT, - number=1, - ) - memory_gb: float = proto.Field( - proto.FLOAT, - number=2, - ) - storage_gb: float = proto.Field( - proto.FLOAT, - number=3, - ) - min_count: int = proto.Field( - proto.INT32, - number=4, - ) - max_count: int = proto.Field( - proto.INT32, - number=5, - ) - - class TriggererResource(proto.Message): - r"""Configuration for resources used by Airflow triggerers. - - Attributes: - count (int): - Optional. The number of triggerers. - cpu (float): - Optional. CPU request and limit for a single - Airflow triggerer replica. - memory_gb (float): - Optional. Memory (GB) request and limit for a - single Airflow triggerer replica. - """ - - count: int = proto.Field( - proto.INT32, - number=1, - ) - cpu: float = proto.Field( - proto.FLOAT, - number=2, - ) - memory_gb: float = proto.Field( - proto.FLOAT, - number=3, - ) - - class DagProcessorResource(proto.Message): - r"""Configuration for resources used by Airflow DAG processors. - - This field is supported for Cloud Composer environments in versions - composer-3-airflow-\ *.*.\ *-build.* and newer. - - Attributes: - cpu (float): - Optional. CPU request and limit for a single - Airflow DAG processor replica. - memory_gb (float): - Optional. Memory (GB) request and limit for a - single Airflow DAG processor replica. - storage_gb (float): - Optional. Storage (GB) request and limit for - a single Airflow DAG processor replica. - count (int): - Optional. The number of DAG processors. If - not provided or set to 0, a single DAG processor - instance will be created. - """ - - cpu: float = proto.Field( - proto.FLOAT, - number=1, - ) - memory_gb: float = proto.Field( - proto.FLOAT, - number=2, - ) - storage_gb: float = proto.Field( - proto.FLOAT, - number=3, - ) - count: int = proto.Field( - proto.INT32, - number=4, - ) - - scheduler: SchedulerResource = proto.Field( - proto.MESSAGE, - number=1, - message=SchedulerResource, - ) - web_server: WebServerResource = proto.Field( - proto.MESSAGE, - number=2, - message=WebServerResource, - ) - worker: WorkerResource = proto.Field( - proto.MESSAGE, - number=3, - message=WorkerResource, - ) - triggerer: TriggererResource = proto.Field( - proto.MESSAGE, - number=4, - message=TriggererResource, - ) - dag_processor: DagProcessorResource = proto.Field( - proto.MESSAGE, - number=5, - message=DagProcessorResource, - ) - - -class DataRetentionConfig(proto.Message): - r"""The configuration setting for Airflow database data retention - mechanism. - - Attributes: - airflow_database_retention_days (int): - Optional. The number of days describing for - how long to store event-based records in airflow - database. If the retention mechanism is enabled - this value must be a positive integer otherwise, - value should be set to 0. - task_logs_retention_config (google.cloud.orchestration.airflow.service_v1beta1.types.TaskLogsRetentionConfig): - Optional. The configuration settings for task - logs retention - airflow_metadata_retention_config (google.cloud.orchestration.airflow.service_v1beta1.types.AirflowMetadataRetentionPolicyConfig): - Optional. The retention policy for airflow - metadata database. - """ - - airflow_database_retention_days: int = proto.Field( - proto.INT32, - number=1, - ) - task_logs_retention_config: 'TaskLogsRetentionConfig' = proto.Field( - proto.MESSAGE, - number=4, - message='TaskLogsRetentionConfig', - ) - airflow_metadata_retention_config: 'AirflowMetadataRetentionPolicyConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='AirflowMetadataRetentionPolicyConfig', - ) - - -class TaskLogsRetentionConfig(proto.Message): - r"""The configuration setting for Task Logs. - - Attributes: - storage_mode (google.cloud.orchestration.airflow.service_v1beta1.types.TaskLogsRetentionConfig.TaskLogsStorageMode): - Optional. The mode of storage for Airflow - workers task logs. - """ - class TaskLogsStorageMode(proto.Enum): - r"""The definition of task_logs_storage_mode. - - Values: - TASK_LOGS_STORAGE_MODE_UNSPECIFIED (0): - This configuration is not specified by the - user. - CLOUD_LOGGING_AND_CLOUD_STORAGE (1): - Store task logs in Cloud Logging and in the - environment's Cloud Storage bucket. - CLOUD_LOGGING_ONLY (2): - Store task logs in Cloud Logging only. - """ - TASK_LOGS_STORAGE_MODE_UNSPECIFIED = 0 - CLOUD_LOGGING_AND_CLOUD_STORAGE = 1 - CLOUD_LOGGING_ONLY = 2 - - storage_mode: TaskLogsStorageMode = proto.Field( - proto.ENUM, - number=2, - enum=TaskLogsStorageMode, - ) - - -class AirflowMetadataRetentionPolicyConfig(proto.Message): - r"""The policy for airflow metadata database retention. - - Attributes: - retention_mode (google.cloud.orchestration.airflow.service_v1beta1.types.AirflowMetadataRetentionPolicyConfig.RetentionMode): - Optional. Retention can be either enabled or - disabled. - retention_days (int): - Optional. How many days data should be - retained for. - """ - class RetentionMode(proto.Enum): - r"""Describes retention policy. - - Values: - RETENTION_MODE_UNSPECIFIED (0): - Default mode doesn't change environment - parameters. - RETENTION_MODE_ENABLED (1): - Retention policy is enabled. - RETENTION_MODE_DISABLED (2): - Retention policy is disabled. - """ - RETENTION_MODE_UNSPECIFIED = 0 - RETENTION_MODE_ENABLED = 1 - RETENTION_MODE_DISABLED = 2 - - retention_mode: RetentionMode = proto.Field( - proto.ENUM, - number=1, - enum=RetentionMode, - ) - retention_days: int = proto.Field( - proto.INT32, - number=2, - ) - - -class StorageConfig(proto.Message): - r"""The configuration for data storage in the environment. - - Attributes: - bucket (str): - Optional. The name of the Cloud Storage bucket used by the - environment. No ``gs://`` prefix. - """ - - bucket: str = proto.Field( - proto.STRING, - number=1, - ) - - -class RecoveryConfig(proto.Message): - r"""The Recovery settings of an environment. - - Attributes: - scheduled_snapshots_config (google.cloud.orchestration.airflow.service_v1beta1.types.ScheduledSnapshotsConfig): - Optional. The configuration for scheduled - snapshot creation mechanism. - """ - - scheduled_snapshots_config: 'ScheduledSnapshotsConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='ScheduledSnapshotsConfig', - ) - - -class ScheduledSnapshotsConfig(proto.Message): - r"""The configuration for scheduled snapshot creation mechanism. - - Attributes: - enabled (bool): - Optional. Whether scheduled snapshots - creation is enabled. - snapshot_location (str): - Optional. The Cloud Storage location for - storing automatically created snapshots. - snapshot_creation_schedule (str): - Optional. The cron expression representing - the time when snapshots creation mechanism runs. - This field is subject to additional validation - around frequency of execution. - time_zone (str): - Optional. Time zone that sets the context to interpret - snapshot_creation_schedule. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - snapshot_location: str = proto.Field( - proto.STRING, - number=6, - ) - snapshot_creation_schedule: str = proto.Field( - proto.STRING, - number=3, - ) - time_zone: str = proto.Field( - proto.STRING, - number=5, - ) - - -class MasterAuthorizedNetworksConfig(proto.Message): - r"""Configuration options for the master authorized networks - feature. Enabled master authorized networks will disallow all - external traffic to access Kubernetes master through HTTPS - except traffic from the given CIDR blocks, Google Compute Engine - Public IPs and Google Prod IPs. - - Attributes: - enabled (bool): - Whether or not master authorized networks - feature is enabled. - cidr_blocks (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.MasterAuthorizedNetworksConfig.CidrBlock]): - Up to 50 external networks that could access - Kubernetes master through HTTPS. - """ - - class CidrBlock(proto.Message): - r"""CIDR block with an optional name. - - Attributes: - display_name (str): - User-defined name that identifies the CIDR - block. - cidr_block (str): - CIDR block that must be specified in CIDR - notation. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - cidr_block: str = proto.Field( - proto.STRING, - number=2, - ) - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - cidr_blocks: MutableSequence[CidrBlock] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=CidrBlock, - ) - - -class CloudDataLineageIntegration(proto.Message): - r"""Configuration for Cloud Data Lineage integration. - - Attributes: - enabled (bool): - Optional. Whether or not Cloud Data Lineage - integration is enabled. - """ - - enabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - - -class Environment(proto.Message): - r"""An environment for running orchestration tasks. - - Attributes: - name (str): - Identifier. The resource name of the - environment, in the form: - "projects/{projectId}/locations/{locationId}/environments/{environmentId}" - - EnvironmentId must start with a lowercase letter - followed by up to 63 lowercase letters, numbers, - or hyphens, and cannot end with a hyphen. - config (google.cloud.orchestration.airflow.service_v1beta1.types.EnvironmentConfig): - Optional. Configuration parameters for this - environment. - uuid (str): - Output only. The UUID (Universally Unique - IDentifier) associated with this environment. - This value is generated when the environment is - created. - state (google.cloud.orchestration.airflow.service_v1beta1.types.Environment.State): - The current state of the environment. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - environment was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - environment was last modified. - labels (MutableMapping[str, str]): - Optional. User-defined labels for this environment. The - labels map can contain no more than 64 entries. Entries of - the labels map are UTF8 strings that comply with the - following restrictions: - - - Keys must conform to regexp: - [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62} - - Values must conform to regexp: - [\p{Ll}\p{Lo}\p{N}_-]{0,63} - - Both keys and values are additionally constrained to be - <= 128 bytes in size. - satisfies_pzs (bool): - Output only. Reserved for future use. - satisfies_pzi (bool): - Output only. Reserved for future use. - storage_config (google.cloud.orchestration.airflow.service_v1beta1.types.StorageConfig): - Optional. Storage configuration for this - environment. - """ - class State(proto.Enum): - r"""State of the environment. - - Values: - STATE_UNSPECIFIED (0): - The state of the environment is unknown. - CREATING (1): - The environment is in the process of being - created. - RUNNING (2): - The environment is currently running and - healthy. It is ready for use. - UPDATING (3): - The environment is being updated. It remains - usable but cannot receive additional update - requests or be deleted at this time. - DELETING (4): - The environment is undergoing deletion. It - cannot be used. - ERROR (5): - The environment has encountered an error and - cannot be used. - """ - STATE_UNSPECIFIED = 0 - CREATING = 1 - RUNNING = 2 - UPDATING = 3 - DELETING = 4 - ERROR = 5 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - config: 'EnvironmentConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='EnvironmentConfig', - ) - uuid: str = proto.Field( - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - satisfies_pzs: bool = proto.Field( - proto.BOOL, - number=8, - ) - satisfies_pzi: bool = proto.Field( - proto.BOOL, - number=10, - ) - storage_config: 'StorageConfig' = proto.Field( - proto.MESSAGE, - number=9, - message='StorageConfig', - ) - - -class CheckUpgradeRequest(proto.Message): - r"""Request to check whether image upgrade will succeed. - - Attributes: - environment (str): - The resource name of the environment to check - upgrade for, in the form: - - "projects/{projectId}/locations/{locationId}/environments/{environmentId}". - image_version (str): - The version of the software running in the environment. This - encapsulates both the version of Cloud Composer - functionality and the version of Apache Airflow. It must - match the regular expression - ``composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)``. - When used as input, the server also checks if the provided - version is supported and denies the request for an - unsupported version. - - The Cloud Composer portion of the image version is a full - `semantic version `__, or an alias in - the form of major version number or ``latest``. When an - alias is provided, the server replaces it with the current - Cloud Composer version that satisfies the alias. - - The Apache Airflow portion of the image version is a full - semantic version that points to one of the supported Apache - Airflow versions, or an alias in the form of only major or - major.minor versions specified. When an alias is provided, - the server replaces it with the latest Apache Airflow - version that satisfies the alias and is supported in the - given Cloud Composer version. - - In all cases, the resolved image version is stored in the - same field. - - See also `version - list `__ - and `versioning - overview `__. - """ - - environment: str = proto.Field( - proto.STRING, - number=1, - ) - image_version: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CheckUpgradeResponse(proto.Message): - r"""Message containing information about the result of an upgrade - check operation. - - Attributes: - build_log_uri (str): - Output only. Url for a docker build log of an - upgraded image. - contains_pypi_modules_conflict (google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeResponse.ConflictResult): - Output only. Whether build has succeeded or - failed on modules conflicts. - pypi_conflict_build_log_extract (str): - Output only. Extract from a docker image - build log containing information about pypi - modules conflicts. - image_version (str): - Composer image for which the build was - happening. - pypi_dependencies (MutableMapping[str, str]): - Pypi dependencies specified in the - environment configuration, at the time when the - build was triggered. - """ - class ConflictResult(proto.Enum): - r"""Whether there were python modules conflict during image - build. - - Values: - CONFLICT_RESULT_UNSPECIFIED (0): - It is unknown whether build had conflicts or - not. - CONFLICT (1): - There were python packages conflicts. - NO_CONFLICT (2): - There were no python packages conflicts. - """ - CONFLICT_RESULT_UNSPECIFIED = 0 - CONFLICT = 1 - NO_CONFLICT = 2 - - build_log_uri: str = proto.Field( - proto.STRING, - number=1, - ) - contains_pypi_modules_conflict: ConflictResult = proto.Field( - proto.ENUM, - number=4, - enum=ConflictResult, - ) - pypi_conflict_build_log_extract: str = proto.Field( - proto.STRING, - number=3, - ) - image_version: str = proto.Field( - proto.STRING, - number=5, - ) - pypi_dependencies: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/image_versions.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/image_versions.py deleted file mode 100644 index 656f44349e78..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/image_versions.py +++ /dev/null @@ -1,148 +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.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.orchestration.airflow.service.v1beta1', - manifest={ - 'ListImageVersionsRequest', - 'ListImageVersionsResponse', - 'ImageVersion', - }, -) - - -class ListImageVersionsRequest(proto.Message): - r"""List ImageVersions in a project and location. - - Attributes: - parent (str): - List ImageVersions in the given project and - location, in the form: - "projects/{projectId}/locations/{locationId}". - page_size (int): - The maximum number of image_versions to return. - page_token (str): - The next_page_token value returned from a previous List - request, if any. - include_past_releases (bool): - Whether or not image versions from old - releases should be included. - """ - - 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, - ) - include_past_releases: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class ListImageVersionsResponse(proto.Message): - r"""The ImageVersions in a project and location. - - Attributes: - image_versions (MutableSequence[google.cloud.orchestration.airflow.service_v1beta1.types.ImageVersion]): - The list of supported ImageVersions in a - location. - next_page_token (str): - The page token used to query for the next - page if one exists. - """ - - @property - def raw_page(self): - return self - - image_versions: MutableSequence['ImageVersion'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ImageVersion', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ImageVersion(proto.Message): - r"""Image Version information - - Attributes: - image_version_id (str): - The string identifier of the ImageVersion, in - the form: "composer-x.y.z-airflow-a.b.c". - is_default (bool): - Whether this is the default ImageVersion used - by Composer during environment creation if no - input ImageVersion is specified. - supported_python_versions (MutableSequence[str]): - supported python versions - release_date (google.type.date_pb2.Date): - The date of the version release. - creation_disabled (bool): - Whether it is impossible to create an - environment with the image version. - upgrade_disabled (bool): - Whether it is impossible to upgrade an - environment running with the image version. - """ - - image_version_id: str = proto.Field( - proto.STRING, - number=1, - ) - is_default: bool = proto.Field( - proto.BOOL, - number=2, - ) - supported_python_versions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - release_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=4, - message=date_pb2.Date, - ) - creation_disabled: bool = proto.Field( - proto.BOOL, - number=5, - ) - upgrade_disabled: bool = proto.Field( - proto.BOOL, - number=6, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py deleted file mode 100644 index 585838b342e6..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py +++ /dev/null @@ -1,143 +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.orchestration.airflow.service.v1beta1', - manifest={ - 'OperationMetadata', - }, -) - - -class OperationMetadata(proto.Message): - r"""Metadata describing an operation. - - Attributes: - state (google.cloud.orchestration.airflow.service_v1beta1.types.OperationMetadata.State): - Output only. The current operation state. - operation_type (google.cloud.orchestration.airflow.service_v1beta1.types.OperationMetadata.Type): - Output only. The type of operation being - performed. - resource (str): - Output only. The resource being operated on, as a `relative - resource - name `__. - resource_uuid (str): - Output only. The UUID of the resource being - operated on. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation was - submitted to the server. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the operation - terminated, regardless of its success. This - field is unset if the operation is still - ongoing. - """ - class State(proto.Enum): - r"""An enum describing the overall state of an operation. - - Values: - STATE_UNSPECIFIED (0): - Unused. - PENDING (1): - The operation has been created but is not yet - started. - RUNNING (2): - The operation is underway. - SUCCESSFUL (3): - The operation completed successfully. - FAILED (4): - The operation is no longer running but did - not succeed. - """ - STATE_UNSPECIFIED = 0 - PENDING = 1 - RUNNING = 2 - SUCCESSFUL = 3 - FAILED = 4 - - class Type(proto.Enum): - r"""Type of longrunning operation. - - Values: - TYPE_UNSPECIFIED (0): - Unused. - CREATE (1): - A resource creation operation. - DELETE (2): - A resource deletion operation. - UPDATE (3): - A resource update operation. - CHECK (4): - A resource check operation. - SAVE_SNAPSHOT (5): - Saves snapshot of the resource operation. - LOAD_SNAPSHOT (6): - Loads snapshot of the resource operation. - DATABASE_FAILOVER (7): - Triggers failover of environment's Cloud SQL - instance (only for highly resilient - environments). - """ - TYPE_UNSPECIFIED = 0 - CREATE = 1 - DELETE = 2 - UPDATE = 3 - CHECK = 4 - SAVE_SNAPSHOT = 5 - LOAD_SNAPSHOT = 6 - DATABASE_FAILOVER = 7 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - operation_type: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - resource: str = proto.Field( - proto.STRING, - number=3, - ) - resource_uuid: str = proto.Field( - proto.STRING, - number=4, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/mypy.ini b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/noxfile.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/noxfile.py deleted file mode 100644 index 45aed3ec3bd0..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow-service' - -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/orchestration/airflow/service_v1beta1/', - '--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/orchestration/airflow/service_v1beta1/', - '--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-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py deleted file mode 100644 index 6baa8c041043..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_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 CheckUpgrade -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_CheckUpgrade_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.orchestration.airflow import service_v1beta1 - - -async def sample_check_upgrade(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.CheckUpgradeRequest( - ) - - # Make the request - operation = client.check_upgrade(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_CheckUpgrade_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py deleted file mode 100644 index 7f42892feecf..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_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 CheckUpgrade -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_CheckUpgrade_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.orchestration.airflow import service_v1beta1 - - -def sample_check_upgrade(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.CheckUpgradeRequest( - ) - - # Make the request - operation = client.check_upgrade(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_CheckUpgrade_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py deleted file mode 100644 index d5cd4346b3ff..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_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 CreateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_CreateEnvironment_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.orchestration.airflow import service_v1beta1 - - -async def sample_create_environment(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateEnvironmentRequest( - ) - - # Make the request - operation = client.create_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_CreateEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py deleted file mode 100644 index e7b8bb84502c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_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 CreateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_CreateEnvironment_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.orchestration.airflow import service_v1beta1 - - -def sample_create_environment(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateEnvironmentRequest( - ) - - # Make the request - operation = client.create_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_CreateEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_async.py deleted file mode 100644 index ced9415f1df3..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_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 CreateUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 - - -async def sample_create_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateUserWorkloadsConfigMapRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_sync.py deleted file mode 100644 index b34964ee1e0b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_config_map_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 CreateUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 - - -def sample_create_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateUserWorkloadsConfigMapRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_async.py deleted file mode 100644 index 806219d891ab..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_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 CreateUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 - - -async def sample_create_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateUserWorkloadsSecretRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_sync.py deleted file mode 100644 index 00ab0b127a15..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_user_workloads_secret_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 CreateUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 - - -def sample_create_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.CreateUserWorkloadsSecretRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py deleted file mode 100644 index 030ec030de2c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_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 DatabaseFailover -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_DatabaseFailover_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.orchestration.airflow import service_v1beta1 - - -async def sample_database_failover(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.DatabaseFailoverRequest( - ) - - # Make the request - operation = client.database_failover(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_DatabaseFailover_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py deleted file mode 100644 index 9ee79ca04dec..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_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 DatabaseFailover -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_DatabaseFailover_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.orchestration.airflow import service_v1beta1 - - -def sample_database_failover(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.DatabaseFailoverRequest( - ) - - # Make the request - operation = client.database_failover(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_DatabaseFailover_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py deleted file mode 100644 index 81e42e44a226..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_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 DeleteEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_DeleteEnvironment_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.orchestration.airflow import service_v1beta1 - - -async def sample_delete_environment(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteEnvironmentRequest( - ) - - # Make the request - operation = client.delete_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_DeleteEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py deleted file mode 100644 index 797acab85ac0..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_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 DeleteEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_DeleteEnvironment_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.orchestration.airflow import service_v1beta1 - - -def sample_delete_environment(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteEnvironmentRequest( - ) - - # Make the request - operation = client.delete_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_DeleteEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py deleted file mode 100644 index 4fd28d601d04..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py +++ /dev/null @@ -1,50 +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 DeleteUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 - - -async def sample_delete_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - await client.delete_user_workloads_config_map(request=request) - - -# [END composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py deleted file mode 100644 index 8666cf16962e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py +++ /dev/null @@ -1,50 +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 DeleteUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 - - -def sample_delete_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - client.delete_user_workloads_config_map(request=request) - - -# [END composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py deleted file mode 100644 index bad25cfa30ca..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py +++ /dev/null @@ -1,50 +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 DeleteUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 - - -async def sample_delete_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - await client.delete_user_workloads_secret(request=request) - - -# [END composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py deleted file mode 100644 index 846c5a894a20..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py +++ /dev/null @@ -1,50 +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 DeleteUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 - - -def sample_delete_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.DeleteUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - client.delete_user_workloads_secret(request=request) - - -# [END composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py deleted file mode 100644 index b9fe11cb8cc4..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExecuteAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_ExecuteAirflowCommand_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.orchestration.airflow import service_v1beta1 - - -async def sample_execute_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ExecuteAirflowCommandRequest( - ) - - # Make the request - response = await client.execute_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_ExecuteAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py deleted file mode 100644 index 092e93e88fa8..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExecuteAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_ExecuteAirflowCommand_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.orchestration.airflow import service_v1beta1 - - -def sample_execute_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.ExecuteAirflowCommandRequest( - ) - - # Make the request - response = client.execute_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_ExecuteAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py deleted file mode 100644 index 57aa9678bc5f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_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 FetchDatabaseProperties -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_FetchDatabaseProperties_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.orchestration.airflow import service_v1beta1 - - -async def sample_fetch_database_properties(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.FetchDatabasePropertiesRequest( - environment="environment_value", - ) - - # Make the request - response = await client.fetch_database_properties(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_FetchDatabaseProperties_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py deleted file mode 100644 index 83de56e5deec..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_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 FetchDatabaseProperties -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_FetchDatabaseProperties_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.orchestration.airflow import service_v1beta1 - - -def sample_fetch_database_properties(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.FetchDatabasePropertiesRequest( - environment="environment_value", - ) - - # Make the request - response = client.fetch_database_properties(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_FetchDatabaseProperties_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py deleted file mode 100644 index 2fd85676181a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_GetEnvironment_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.orchestration.airflow import service_v1beta1 - - -async def sample_get_environment(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.GetEnvironmentRequest( - ) - - # Make the request - response = await client.get_environment(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_GetEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py deleted file mode 100644 index 5848891a5a2f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_GetEnvironment_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.orchestration.airflow import service_v1beta1 - - -def sample_get_environment(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.GetEnvironmentRequest( - ) - - # Make the request - response = client.get_environment(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_GetEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_async.py deleted file mode 100644 index db6fe57f2cb0..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_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 GetUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 - - -async def sample_get_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.GetUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_sync.py deleted file mode 100644 index 03fdda66a9e0..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_config_map_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 GetUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 - - -def sample_get_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.GetUserWorkloadsConfigMapRequest( - name="name_value", - ) - - # Make the request - response = client.get_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_async.py deleted file mode 100644 index c415f1ba12ac..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_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 GetUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 - - -async def sample_get_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.GetUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_sync.py deleted file mode 100644 index d7e634fc392f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_user_workloads_secret_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 GetUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 - - -def sample_get_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.GetUserWorkloadsSecretRequest( - name="name_value", - ) - - # Make the request - response = client.get_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py deleted file mode 100644 index accc178dfc2f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_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 ListEnvironments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_ListEnvironments_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.orchestration.airflow import service_v1beta1 - - -async def sample_list_environments(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ListEnvironmentsRequest( - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END composer_v1beta1_generated_Environments_ListEnvironments_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py deleted file mode 100644 index 62b54c259c23..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_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 ListEnvironments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_ListEnvironments_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.orchestration.airflow import service_v1beta1 - - -def sample_list_environments(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.ListEnvironmentsRequest( - ) - - # Make the request - page_result = client.list_environments(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END composer_v1beta1_generated_Environments_ListEnvironments_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_async.py deleted file mode 100644 index 6911e8a42394..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_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 ListUserWorkloadsConfigMaps -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_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.orchestration.airflow import service_v1beta1 - - -async def sample_list_user_workloads_config_maps(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ListUserWorkloadsConfigMapsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_config_maps(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_sync.py deleted file mode 100644 index 80f6c060f7fb..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_config_maps_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 ListUserWorkloadsConfigMaps -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_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.orchestration.airflow import service_v1beta1 - - -def sample_list_user_workloads_config_maps(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.ListUserWorkloadsConfigMapsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_config_maps(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_async.py deleted file mode 100644 index 4e0fde2889ef..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_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 ListUserWorkloadsSecrets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_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.orchestration.airflow import service_v1beta1 - - -async def sample_list_user_workloads_secrets(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ListUserWorkloadsSecretsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_secrets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_sync.py deleted file mode 100644 index df5ea329609c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_user_workloads_secrets_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 ListUserWorkloadsSecrets -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_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.orchestration.airflow import service_v1beta1 - - -def sample_list_user_workloads_secrets(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.ListUserWorkloadsSecretsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_user_workloads_secrets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_async.py deleted file mode 100644 index ce4aeeea2e44..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_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 ListWorkloads -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_ListWorkloads_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.orchestration.airflow import service_v1beta1 - - -async def sample_list_workloads(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ListWorkloadsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workloads(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END composer_v1beta1_generated_Environments_ListWorkloads_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_sync.py deleted file mode 100644 index eef4cf388e9d..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_workloads_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 ListWorkloads -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_ListWorkloads_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.orchestration.airflow import service_v1beta1 - - -def sample_list_workloads(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.ListWorkloadsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_workloads(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END composer_v1beta1_generated_Environments_ListWorkloads_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py deleted file mode 100644 index 3c74e656e14a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_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 LoadSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_LoadSnapshot_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.orchestration.airflow import service_v1beta1 - - -async def sample_load_snapshot(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.LoadSnapshotRequest( - ) - - # Make the request - operation = client.load_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_LoadSnapshot_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py deleted file mode 100644 index 2c6363265456..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_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 LoadSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_LoadSnapshot_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.orchestration.airflow import service_v1beta1 - - -def sample_load_snapshot(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.LoadSnapshotRequest( - ) - - # Make the request - operation = client.load_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_LoadSnapshot_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py deleted file mode 100644 index 72f7769e2133..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PollAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_PollAirflowCommand_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.orchestration.airflow import service_v1beta1 - - -async def sample_poll_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.PollAirflowCommandRequest( - ) - - # Make the request - response = await client.poll_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_PollAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py deleted file mode 100644 index 9d3cac31ca45..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PollAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_PollAirflowCommand_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.orchestration.airflow import service_v1beta1 - - -def sample_poll_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.PollAirflowCommandRequest( - ) - - # Make the request - response = client.poll_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_PollAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py deleted file mode 100644 index 7c3695c9c059..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_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 RestartWebServer -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_RestartWebServer_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.orchestration.airflow import service_v1beta1 - - -async def sample_restart_web_server(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.RestartWebServerRequest( - ) - - # Make the request - operation = client.restart_web_server(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_RestartWebServer_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py deleted file mode 100644 index 45bdc32d4414..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_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 RestartWebServer -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_RestartWebServer_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.orchestration.airflow import service_v1beta1 - - -def sample_restart_web_server(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.RestartWebServerRequest( - ) - - # Make the request - operation = client.restart_web_server(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_RestartWebServer_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py deleted file mode 100644 index e1633fb95150..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_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 SaveSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_SaveSnapshot_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.orchestration.airflow import service_v1beta1 - - -async def sample_save_snapshot(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.SaveSnapshotRequest( - ) - - # Make the request - operation = client.save_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_SaveSnapshot_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py deleted file mode 100644 index 2cc6efa01f67..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_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 SaveSnapshot -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_SaveSnapshot_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.orchestration.airflow import service_v1beta1 - - -def sample_save_snapshot(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.SaveSnapshotRequest( - ) - - # Make the request - operation = client.save_snapshot(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_SaveSnapshot_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py deleted file mode 100644 index fb9f01196fa1..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StopAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_StopAirflowCommand_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.orchestration.airflow import service_v1beta1 - - -async def sample_stop_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.StopAirflowCommandRequest( - ) - - # Make the request - response = await client.stop_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_StopAirflowCommand_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py deleted file mode 100644 index 04af2493c240..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for StopAirflowCommand -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_StopAirflowCommand_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.orchestration.airflow import service_v1beta1 - - -def sample_stop_airflow_command(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.StopAirflowCommandRequest( - ) - - # Make the request - response = client.stop_airflow_command(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_StopAirflowCommand_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py deleted file mode 100644 index 2ca35a97a361..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_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 UpdateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_UpdateEnvironment_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.orchestration.airflow import service_v1beta1 - - -async def sample_update_environment(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateEnvironmentRequest( - ) - - # Make the request - operation = client.update_environment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_UpdateEnvironment_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py deleted file mode 100644 index 8414feba820a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_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 UpdateEnvironment -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_UpdateEnvironment_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.orchestration.airflow import service_v1beta1 - - -def sample_update_environment(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateEnvironmentRequest( - ) - - # Make the request - operation = client.update_environment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_UpdateEnvironment_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py deleted file mode 100644 index e14bc1342606..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 - - -async def sample_update_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateUserWorkloadsConfigMapRequest( - ) - - # Make the request - response = await client.update_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py deleted file mode 100644 index 5bc57738762e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUserWorkloadsConfigMap -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_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.orchestration.airflow import service_v1beta1 - - -def sample_update_user_workloads_config_map(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateUserWorkloadsConfigMapRequest( - ) - - # Make the request - response = client.update_user_workloads_config_map(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_async.py deleted file mode 100644 index e200b6782d9c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 - - -async def sample_update_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateUserWorkloadsSecretRequest( - ) - - # Make the request - response = await client.update_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py deleted file mode 100644 index 50022404644a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUserWorkloadsSecret -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_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.orchestration.airflow import service_v1beta1 - - -def sample_update_user_workloads_secret(): - # Create a client - client = service_v1beta1.EnvironmentsClient() - - # Initialize request argument(s) - request = service_v1beta1.UpdateUserWorkloadsSecretRequest( - ) - - # Make the request - response = client.update_user_workloads_secret(request=request) - - # Handle the response - print(response) - -# [END composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_async.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_async.py deleted file mode 100644 index 309c6f9eeab4..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_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 ListImageVersions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_ImageVersions_ListImageVersions_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.orchestration.airflow import service_v1beta1 - - -async def sample_list_image_versions(): - # Create a client - client = service_v1beta1.ImageVersionsAsyncClient() - - # Initialize request argument(s) - request = service_v1beta1.ListImageVersionsRequest( - ) - - # Make the request - page_result = client.list_image_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END composer_v1beta1_generated_ImageVersions_ListImageVersions_async] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_sync.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_sync.py deleted file mode 100644 index 86a3b0c52064..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_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 ListImageVersions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-orchestration-airflow-service - - -# [START composer_v1beta1_generated_ImageVersions_ListImageVersions_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.orchestration.airflow import service_v1beta1 - - -def sample_list_image_versions(): - # Create a client - client = service_v1beta1.ImageVersionsClient() - - # Initialize request argument(s) - request = service_v1beta1.ListImageVersionsRequest( - ) - - # Make the request - page_result = client.list_image_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END composer_v1beta1_generated_ImageVersions_ListImageVersions_sync] diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json deleted file mode 100644 index 5dde9a47fdfc..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json +++ /dev/null @@ -1,4157 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.orchestration.airflow.service.v1beta1", - "version": "v1beta1" - } - ], - "language": "PYTHON", - "name": "google-cloud-orchestration-airflow-service", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.check_upgrade", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CheckUpgrade", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "CheckUpgrade" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeRequest" - }, - { - "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": "check_upgrade" - }, - "description": "Sample for CheckUpgrade", - "file": "composer_v1beta1_generated_environments_check_upgrade_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_CheckUpgrade_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_check_upgrade_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.check_upgrade", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CheckUpgrade", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "CheckUpgrade" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CheckUpgradeRequest" - }, - { - "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": "check_upgrade" - }, - "description": "Sample for CheckUpgrade", - "file": "composer_v1beta1_generated_environments_check_upgrade_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_CheckUpgrade_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_check_upgrade_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.create_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateEnvironmentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "environment", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.Environment" - }, - { - "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_environment" - }, - "description": "Sample for CreateEnvironment", - "file": "composer_v1beta1_generated_environments_create_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_CreateEnvironment_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_create_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateEnvironmentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "environment", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.Environment" - }, - { - "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_environment" - }, - "description": "Sample for CreateEnvironment", - "file": "composer_v1beta1_generated_environments_create_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_CreateEnvironment_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_create_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.create_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsConfigMapRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user_workloads_config_map", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", - "shortName": "create_user_workloads_config_map" - }, - "description": "Sample for CreateUserWorkloadsConfigMap", - "file": "composer_v1beta1_generated_environments_create_user_workloads_config_map_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_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": "composer_v1beta1_generated_environments_create_user_workloads_config_map_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsConfigMapRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user_workloads_config_map", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", - "shortName": "create_user_workloads_config_map" - }, - "description": "Sample for CreateUserWorkloadsConfigMap", - "file": "composer_v1beta1_generated_environments_create_user_workloads_config_map_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_CreateUserWorkloadsConfigMap_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": "composer_v1beta1_generated_environments_create_user_workloads_config_map_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.create_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsSecretRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user_workloads_secret", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", - "shortName": "create_user_workloads_secret" - }, - "description": "Sample for CreateUserWorkloadsSecret", - "file": "composer_v1beta1_generated_environments_create_user_workloads_secret_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_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": "composer_v1beta1_generated_environments_create_user_workloads_secret_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.create_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.CreateUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "CreateUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.CreateUserWorkloadsSecretRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user_workloads_secret", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", - "shortName": "create_user_workloads_secret" - }, - "description": "Sample for CreateUserWorkloadsSecret", - "file": "composer_v1beta1_generated_environments_create_user_workloads_secret_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_CreateUserWorkloadsSecret_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": "composer_v1beta1_generated_environments_create_user_workloads_secret_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.database_failover", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DatabaseFailover", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "DatabaseFailover" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseFailoverRequest" - }, - { - "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": "database_failover" - }, - "description": "Sample for DatabaseFailover", - "file": "composer_v1beta1_generated_environments_database_failover_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_DatabaseFailover_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_database_failover_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.database_failover", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DatabaseFailover", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "DatabaseFailover" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DatabaseFailoverRequest" - }, - { - "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": "database_failover" - }, - "description": "Sample for DatabaseFailover", - "file": "composer_v1beta1_generated_environments_database_failover_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_DatabaseFailover_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_database_failover_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.delete_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteEnvironmentRequest" - }, - { - "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_environment" - }, - "description": "Sample for DeleteEnvironment", - "file": "composer_v1beta1_generated_environments_delete_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_DeleteEnvironment_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_delete_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.delete_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteEnvironmentRequest" - }, - { - "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_environment" - }, - "description": "Sample for DeleteEnvironment", - "file": "composer_v1beta1_generated_environments_delete_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_DeleteEnvironment_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_delete_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.delete_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsConfigMapRequest" - }, - { - "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]]]" - } - ], - "shortName": "delete_user_workloads_config_map" - }, - "description": "Sample for DeleteUserWorkloadsConfigMap", - "file": "composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_delete_user_workloads_config_map_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.delete_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsConfigMapRequest" - }, - { - "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]]]" - } - ], - "shortName": "delete_user_workloads_config_map" - }, - "description": "Sample for DeleteUserWorkloadsConfigMap", - "file": "composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_DeleteUserWorkloadsConfigMap_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_delete_user_workloads_config_map_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.delete_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsSecretRequest" - }, - { - "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]]]" - } - ], - "shortName": "delete_user_workloads_secret" - }, - "description": "Sample for DeleteUserWorkloadsSecret", - "file": "composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_delete_user_workloads_secret_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.delete_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "DeleteUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteUserWorkloadsSecretRequest" - }, - { - "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]]]" - } - ], - "shortName": "delete_user_workloads_secret" - }, - "description": "Sample for DeleteUserWorkloadsSecret", - "file": "composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_DeleteUserWorkloadsSecret_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_delete_user_workloads_secret_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.execute_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ExecuteAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ExecuteAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandResponse", - "shortName": "execute_airflow_command" - }, - "description": "Sample for ExecuteAirflowCommand", - "file": "composer_v1beta1_generated_environments_execute_airflow_command_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ExecuteAirflowCommand_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_execute_airflow_command_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.execute_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ExecuteAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ExecuteAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.ExecuteAirflowCommandResponse", - "shortName": "execute_airflow_command" - }, - "description": "Sample for ExecuteAirflowCommand", - "file": "composer_v1beta1_generated_environments_execute_airflow_command_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ExecuteAirflowCommand_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_execute_airflow_command_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.fetch_database_properties", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.FetchDatabaseProperties", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "FetchDatabaseProperties" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesResponse", - "shortName": "fetch_database_properties" - }, - "description": "Sample for FetchDatabaseProperties", - "file": "composer_v1beta1_generated_environments_fetch_database_properties_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_FetchDatabaseProperties_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": "composer_v1beta1_generated_environments_fetch_database_properties_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.fetch_database_properties", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.FetchDatabaseProperties", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "FetchDatabaseProperties" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.FetchDatabasePropertiesResponse", - "shortName": "fetch_database_properties" - }, - "description": "Sample for FetchDatabaseProperties", - "file": "composer_v1beta1_generated_environments_fetch_database_properties_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_FetchDatabaseProperties_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": "composer_v1beta1_generated_environments_fetch_database_properties_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.get_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.types.Environment", - "shortName": "get_environment" - }, - "description": "Sample for GetEnvironment", - "file": "composer_v1beta1_generated_environments_get_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_GetEnvironment_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_get_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "GetEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.types.Environment", - "shortName": "get_environment" - }, - "description": "Sample for GetEnvironment", - "file": "composer_v1beta1_generated_environments_get_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_GetEnvironment_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_get_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.get_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "GetUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsConfigMapRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", - "shortName": "get_user_workloads_config_map" - }, - "description": "Sample for GetUserWorkloadsConfigMap", - "file": "composer_v1beta1_generated_environments_get_user_workloads_config_map_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_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": "composer_v1beta1_generated_environments_get_user_workloads_config_map_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "GetUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsConfigMapRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", - "shortName": "get_user_workloads_config_map" - }, - "description": "Sample for GetUserWorkloadsConfigMap", - "file": "composer_v1beta1_generated_environments_get_user_workloads_config_map_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_GetUserWorkloadsConfigMap_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": "composer_v1beta1_generated_environments_get_user_workloads_config_map_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.get_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "GetUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsSecretRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", - "shortName": "get_user_workloads_secret" - }, - "description": "Sample for GetUserWorkloadsSecret", - "file": "composer_v1beta1_generated_environments_get_user_workloads_secret_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_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": "composer_v1beta1_generated_environments_get_user_workloads_secret_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "GetUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetUserWorkloadsSecretRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", - "shortName": "get_user_workloads_secret" - }, - "description": "Sample for GetUserWorkloadsSecret", - "file": "composer_v1beta1_generated_environments_get_user_workloads_secret_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_GetUserWorkloadsSecret_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": "composer_v1beta1_generated_environments_get_user_workloads_secret_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.list_environments", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListEnvironments", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ListEnvironments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsAsyncPager", - "shortName": "list_environments" - }, - "description": "Sample for ListEnvironments", - "file": "composer_v1beta1_generated_environments_list_environments_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ListEnvironments_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_list_environments_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_environments", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListEnvironments", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ListEnvironments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsPager", - "shortName": "list_environments" - }, - "description": "Sample for ListEnvironments", - "file": "composer_v1beta1_generated_environments_list_environments_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ListEnvironments_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_list_environments_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.list_user_workloads_config_maps", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListUserWorkloadsConfigMaps", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ListUserWorkloadsConfigMaps" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsConfigMapsAsyncPager", - "shortName": "list_user_workloads_config_maps" - }, - "description": "Sample for ListUserWorkloadsConfigMaps", - "file": "composer_v1beta1_generated_environments_list_user_workloads_config_maps_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_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": "composer_v1beta1_generated_environments_list_user_workloads_config_maps_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_user_workloads_config_maps", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListUserWorkloadsConfigMaps", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ListUserWorkloadsConfigMaps" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsConfigMapsPager", - "shortName": "list_user_workloads_config_maps" - }, - "description": "Sample for ListUserWorkloadsConfigMaps", - "file": "composer_v1beta1_generated_environments_list_user_workloads_config_maps_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ListUserWorkloadsConfigMaps_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": "composer_v1beta1_generated_environments_list_user_workloads_config_maps_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.list_user_workloads_secrets", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListUserWorkloadsSecrets", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ListUserWorkloadsSecrets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsSecretsAsyncPager", - "shortName": "list_user_workloads_secrets" - }, - "description": "Sample for ListUserWorkloadsSecrets", - "file": "composer_v1beta1_generated_environments_list_user_workloads_secrets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_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": "composer_v1beta1_generated_environments_list_user_workloads_secrets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_user_workloads_secrets", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListUserWorkloadsSecrets", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ListUserWorkloadsSecrets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListUserWorkloadsSecretsPager", - "shortName": "list_user_workloads_secrets" - }, - "description": "Sample for ListUserWorkloadsSecrets", - "file": "composer_v1beta1_generated_environments_list_user_workloads_secrets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ListUserWorkloadsSecrets_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": "composer_v1beta1_generated_environments_list_user_workloads_secrets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.list_workloads", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListWorkloads", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ListWorkloads" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListWorkloadsAsyncPager", - "shortName": "list_workloads" - }, - "description": "Sample for ListWorkloads", - "file": "composer_v1beta1_generated_environments_list_workloads_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ListWorkloads_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": "composer_v1beta1_generated_environments_list_workloads_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_workloads", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListWorkloads", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "ListWorkloads" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.services.environments.pagers.ListWorkloadsPager", - "shortName": "list_workloads" - }, - "description": "Sample for ListWorkloads", - "file": "composer_v1beta1_generated_environments_list_workloads_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ListWorkloads_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": "composer_v1beta1_generated_environments_list_workloads_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.load_snapshot", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.LoadSnapshot", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "LoadSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest" - }, - { - "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": "load_snapshot" - }, - "description": "Sample for LoadSnapshot", - "file": "composer_v1beta1_generated_environments_load_snapshot_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_LoadSnapshot_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_load_snapshot_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.load_snapshot", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.LoadSnapshot", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "LoadSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest" - }, - { - "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": "load_snapshot" - }, - "description": "Sample for LoadSnapshot", - "file": "composer_v1beta1_generated_environments_load_snapshot_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_LoadSnapshot_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_load_snapshot_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.poll_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.PollAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "PollAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse", - "shortName": "poll_airflow_command" - }, - "description": "Sample for PollAirflowCommand", - "file": "composer_v1beta1_generated_environments_poll_airflow_command_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_PollAirflowCommand_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_poll_airflow_command_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.poll_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.PollAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "PollAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse", - "shortName": "poll_airflow_command" - }, - "description": "Sample for PollAirflowCommand", - "file": "composer_v1beta1_generated_environments_poll_airflow_command_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_PollAirflowCommand_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_poll_airflow_command_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.restart_web_server", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.RestartWebServer", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "RestartWebServer" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest" - }, - { - "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": "restart_web_server" - }, - "description": "Sample for RestartWebServer", - "file": "composer_v1beta1_generated_environments_restart_web_server_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_RestartWebServer_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_restart_web_server_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.restart_web_server", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.RestartWebServer", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "RestartWebServer" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest" - }, - { - "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": "restart_web_server" - }, - "description": "Sample for RestartWebServer", - "file": "composer_v1beta1_generated_environments_restart_web_server_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_RestartWebServer_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_restart_web_server_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.save_snapshot", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.SaveSnapshot", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "SaveSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest" - }, - { - "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": "save_snapshot" - }, - "description": "Sample for SaveSnapshot", - "file": "composer_v1beta1_generated_environments_save_snapshot_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_SaveSnapshot_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_save_snapshot_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.save_snapshot", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.SaveSnapshot", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "SaveSnapshot" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest" - }, - { - "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": "save_snapshot" - }, - "description": "Sample for SaveSnapshot", - "file": "composer_v1beta1_generated_environments_save_snapshot_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_SaveSnapshot_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_save_snapshot_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.stop_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.StopAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "StopAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse", - "shortName": "stop_airflow_command" - }, - "description": "Sample for StopAirflowCommand", - "file": "composer_v1beta1_generated_environments_stop_airflow_command_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_StopAirflowCommand_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_stop_airflow_command_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.stop_airflow_command", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.StopAirflowCommand", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "StopAirflowCommand" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse", - "shortName": "stop_airflow_command" - }, - "description": "Sample for StopAirflowCommand", - "file": "composer_v1beta1_generated_environments_stop_airflow_command_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_StopAirflowCommand_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_stop_airflow_command_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.update_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateEnvironmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "environment", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.Environment" - }, - { - "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_environment" - }, - "description": "Sample for UpdateEnvironment", - "file": "composer_v1beta1_generated_environments_update_environment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_UpdateEnvironment_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_update_environment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_environment", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateEnvironment", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateEnvironment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateEnvironmentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "environment", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.Environment" - }, - { - "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_environment" - }, - "description": "Sample for UpdateEnvironment", - "file": "composer_v1beta1_generated_environments_update_environment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_UpdateEnvironment_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_update_environment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.update_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsConfigMapRequest" - }, - { - "name": "user_workloads_config_map", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", - "shortName": "update_user_workloads_config_map" - }, - "description": "Sample for UpdateUserWorkloadsConfigMap", - "file": "composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_update_user_workloads_config_map_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_user_workloads_config_map", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateUserWorkloadsConfigMap", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateUserWorkloadsConfigMap" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsConfigMapRequest" - }, - { - "name": "user_workloads_config_map", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsConfigMap", - "shortName": "update_user_workloads_config_map" - }, - "description": "Sample for UpdateUserWorkloadsConfigMap", - "file": "composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_UpdateUserWorkloadsConfigMap_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_update_user_workloads_config_map_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", - "shortName": "EnvironmentsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.update_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsSecretRequest" - }, - { - "name": "user_workloads_secret", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", - "shortName": "update_user_workloads_secret" - }, - "description": "Sample for UpdateUserWorkloadsSecret", - "file": "composer_v1beta1_generated_environments_update_user_workloads_secret_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_update_user_workloads_secret_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", - "shortName": "EnvironmentsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.update_user_workloads_secret", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.UpdateUserWorkloadsSecret", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", - "shortName": "Environments" - }, - "shortName": "UpdateUserWorkloadsSecret" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UpdateUserWorkloadsSecretRequest" - }, - { - "name": "user_workloads_secret", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.UserWorkloadsSecret", - "shortName": "update_user_workloads_secret" - }, - "description": "Sample for UpdateUserWorkloadsSecret", - "file": "composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_UpdateUserWorkloadsSecret_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_environments_update_user_workloads_secret_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.ImageVersionsAsyncClient", - "shortName": "ImageVersionsAsyncClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.ImageVersionsAsyncClient.list_image_versions", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions.ListImageVersions", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "shortName": "ImageVersions" - }, - "shortName": "ListImageVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.services.image_versions.pagers.ListImageVersionsAsyncPager", - "shortName": "list_image_versions" - }, - "description": "Sample for ListImageVersions", - "file": "composer_v1beta1_generated_image_versions_list_image_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_ImageVersions_ListImageVersions_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_image_versions_list_image_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.ImageVersionsClient", - "shortName": "ImageVersionsClient" - }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.ImageVersionsClient.list_image_versions", - "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions.ListImageVersions", - "service": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.ImageVersions", - "shortName": "ImageVersions" - }, - "shortName": "ListImageVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest" - }, - { - "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.orchestration.airflow.service_v1beta1.services.image_versions.pagers.ListImageVersionsPager", - "shortName": "list_image_versions" - }, - "description": "Sample for ListImageVersions", - "file": "composer_v1beta1_generated_image_versions_list_image_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_ImageVersions_ListImageVersions_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "composer_v1beta1_generated_image_versions_list_image_versions_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py deleted file mode 100644 index 14f61f63b516..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py +++ /dev/null @@ -1,201 +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 serviceCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'check_upgrade': ('environment', 'image_version', ), - 'create_environment': ('parent', 'environment', ), - 'create_user_workloads_config_map': ('parent', 'user_workloads_config_map', ), - 'create_user_workloads_secret': ('parent', 'user_workloads_secret', ), - 'database_failover': ('environment', ), - 'delete_environment': ('name', ), - 'delete_user_workloads_config_map': ('name', ), - 'delete_user_workloads_secret': ('name', ), - 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), - 'fetch_database_properties': ('environment', ), - 'get_environment': ('name', ), - 'get_user_workloads_config_map': ('name', ), - 'get_user_workloads_secret': ('name', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), - 'list_user_workloads_config_maps': ('parent', 'page_size', 'page_token', ), - 'list_user_workloads_secrets': ('parent', 'page_size', 'page_token', ), - 'list_workloads': ('parent', 'page_size', 'page_token', 'filter', ), - 'load_snapshot': ('environment', 'snapshot_path', 'skip_pypi_packages_installation', 'skip_environment_variables_setting', 'skip_airflow_overrides_setting', 'skip_gcs_data_copying', ), - 'poll_airflow_command': ('environment', 'execution_id', 'pod', 'pod_namespace', 'next_line_number', ), - 'restart_web_server': ('name', ), - 'save_snapshot': ('environment', 'snapshot_location', ), - 'stop_airflow_command': ('environment', 'execution_id', 'pod', 'pod_namespace', 'force', ), - 'update_environment': ('update_mask', 'name', 'environment', ), - 'update_user_workloads_config_map': ('user_workloads_config_map', ), - 'update_user_workloads_secret': ('user_workloads_secret', ), - } - - 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=serviceCallTransformer(), -): - """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 service 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-orchestration-airflow/v1beta1/setup.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/setup.py deleted file mode 100644 index 2e2dec3073ba..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow-service' - - -description = "Google Cloud Orchestration Airflow Service API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/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.0,!=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.0,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0", - "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", - "protobuf>=3.20.2,<7.0.0,!=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-orchestration-airflow-service" - -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-orchestration-airflow/v1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt deleted file mode 100644 index a77f12bc13e4..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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.0", -# 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-orchestration-airflow/v1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/__init__.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/__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-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py deleted file mode 100644 index 80fe2db8e672..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py +++ /dev/null @@ -1,17816 +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.orchestration.airflow.service_v1beta1.services.environments import EnvironmentsAsyncClient -from google.cloud.orchestration.airflow.service_v1beta1.services.environments import EnvironmentsClient -from google.cloud.orchestration.airflow.service_v1beta1.services.environments import pagers -from google.cloud.orchestration.airflow.service_v1beta1.services.environments import transports -from google.cloud.orchestration.airflow.service_v1beta1.types import environments -from google.cloud.orchestration.airflow.service_v1beta1.types import operations -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 - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) - - -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 EnvironmentsClient._get_default_mtls_endpoint(None) is None - assert EnvironmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EnvironmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert EnvironmentsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - EnvironmentsClient._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 EnvironmentsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert EnvironmentsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert EnvironmentsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - EnvironmentsClient._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 EnvironmentsClient._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 EnvironmentsClient._get_client_cert_source(None, False) is None - assert EnvironmentsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert EnvironmentsClient._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 EnvironmentsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert EnvironmentsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = EnvironmentsClient._DEFAULT_UNIVERSE - default_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert EnvironmentsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert EnvironmentsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "always") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - assert EnvironmentsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - assert EnvironmentsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert EnvironmentsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - EnvironmentsClient._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 EnvironmentsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert EnvironmentsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert EnvironmentsClient._get_universe_domain(None, None) == EnvironmentsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - EnvironmentsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) -def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): - cred = mock.Mock(["get_cred_info"]) - cred.get_cred_info = mock.Mock(return_value=cred_info_json) - client = EnvironmentsClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401,403,404,500]) -def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): - cred = mock.Mock([]) - assert not hasattr(cred, "get_cred_info") - client = EnvironmentsClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -@pytest.mark.parametrize("client_class,transport_name", [ - (EnvironmentsClient, "grpc"), - (EnvironmentsAsyncClient, "grpc_asyncio"), - (EnvironmentsClient, "rest"), -]) -def test_environments_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 == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://composer.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EnvironmentsGrpcTransport, "grpc"), - (transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EnvironmentsRestTransport, "rest"), -]) -def test_environments_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", [ - (EnvironmentsClient, "grpc"), - (EnvironmentsAsyncClient, "grpc_asyncio"), - (EnvironmentsClient, "rest"), -]) -def test_environments_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 == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://composer.googleapis.com' - ) - - -def test_environments_client_get_transport_class(): - transport = EnvironmentsClient.get_transport_class() - available_transports = [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsRestTransport, - ] - assert transport in available_transports - - transport = EnvironmentsClient.get_transport_class("grpc") - assert transport == transports.EnvironmentsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), -]) -@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) -def test_environments_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(EnvironmentsClient, '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(EnvironmentsClient, '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", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "true"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", "false"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "true"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", "false"), -]) -@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_environments_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", [ - EnvironmentsClient, EnvironmentsAsyncClient -]) -@mock.patch.object(EnvironmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EnvironmentsAsyncClient)) -def test_environments_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", [ - EnvironmentsClient, EnvironmentsAsyncClient -]) -@mock.patch.object(EnvironmentsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EnvironmentsAsyncClient)) -def test_environments_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = EnvironmentsClient._DEFAULT_UNIVERSE - default_endpoint = EnvironmentsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EnvironmentsClient._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", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), -]) -def test_environments_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", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest", None), -]) -def test_environments_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_environments_client_client_options_from_dict(): - with mock.patch('google.cloud.orchestration.airflow.service_v1beta1.services.environments.transports.EnvironmentsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EnvironmentsClient( - 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", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc", grpc_helpers), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_environments_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( - "composer.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="composer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateEnvironmentRequest, - dict, -]) -def test_create_environment(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.CreateEnvironmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_environment_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 = EnvironmentsClient( - 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 = environments.CreateEnvironmentRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_environment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateEnvironmentRequest( - parent='parent_value', - ) - -def test_create_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - request = {} - client.create_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( - 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_environment 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_environment] = mock_rpc - - request = {} - await client.create_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.CreateEnvironmentRequest): - client = EnvironmentsAsyncClient( - 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_environment), - '__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_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.CreateEnvironmentRequest() - 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_environment_async_from_dict(): - await test_create_environment_async(request_type=dict) - -def test_create_environment_field_headers(): - client = EnvironmentsClient( - 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 = environments.CreateEnvironmentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_environment(request) - - # Establish that the 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_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.CreateEnvironmentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_environment(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_environment_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__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_environment( - parent='parent_value', - environment=environments.Environment(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].environment - mock_val = environments.Environment(name='name_value') - assert arg == mock_val - - -def test_create_environment_flattened_error(): - client = EnvironmentsClient( - 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_environment( - environments.CreateEnvironmentRequest(), - parent='parent_value', - environment=environments.Environment(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_environment_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__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_environment( - parent='parent_value', - environment=environments.Environment(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].environment - mock_val = environments.Environment(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_environment_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_environment( - environments.CreateEnvironmentRequest(), - parent='parent_value', - environment=environments.Environment(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetEnvironmentRequest, - dict, -]) -def test_get_environment(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.Environment( - name='name_value', - uuid='uuid_value', - state=environments.Environment.State.CREATING, - satisfies_pzs=True, - satisfies_pzi=True, - ) - response = client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.GetEnvironmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.Environment) - assert response.name == 'name_value' - assert response.uuid == 'uuid_value' - assert response.state == environments.Environment.State.CREATING - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - - -def test_get_environment_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 = EnvironmentsClient( - 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 = environments.GetEnvironmentRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_environment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetEnvironmentRequest( - name='name_value', - ) - -def test_get_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - request = {} - client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_environment(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_environment_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 = EnvironmentsAsyncClient( - 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_environment 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_environment] = mock_rpc - - request = {} - await client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.GetEnvironmentRequest): - client = EnvironmentsAsyncClient( - 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_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment( - name='name_value', - uuid='uuid_value', - state=environments.Environment.State.CREATING, - satisfies_pzs=True, - satisfies_pzi=True, - )) - response = await client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.GetEnvironmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.Environment) - assert response.name == 'name_value' - assert response.uuid == 'uuid_value' - assert response.state == environments.Environment.State.CREATING - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - - -@pytest.mark.asyncio -async def test_get_environment_async_from_dict(): - await test_get_environment_async(request_type=dict) - -def test_get_environment_field_headers(): - client = EnvironmentsClient( - 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 = environments.GetEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value = environments.Environment() - client.get_environment(request) - - # Establish that the 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_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.GetEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment()) - await client.get_environment(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_environment_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.Environment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_environment( - 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_environment_flattened_error(): - client = EnvironmentsClient( - 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_environment( - environments.GetEnvironmentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_environment_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.Environment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_environment( - 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_environment_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_environment( - environments.GetEnvironmentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListEnvironmentsRequest, - dict, -]) -def test_list_environments(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListEnvironmentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.ListEnvironmentsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_environments_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 = EnvironmentsClient( - 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 = environments.ListEnvironmentsRequest( - 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_environments), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_environments(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListEnvironmentsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_environments_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 = EnvironmentsClient( - 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_environments 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_environments] = mock_rpc - request = {} - client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_environments(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_environments_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 = EnvironmentsAsyncClient( - 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_environments 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_environments] = mock_rpc - - request = {} - await client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_environments(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_environments_async(transport: str = 'grpc_asyncio', request_type=environments.ListEnvironmentsRequest): - client = EnvironmentsAsyncClient( - 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_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.ListEnvironmentsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_environments_async_from_dict(): - await test_list_environments_async(request_type=dict) - -def test_list_environments_field_headers(): - client = EnvironmentsClient( - 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 = environments.ListEnvironmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - call.return_value = environments.ListEnvironmentsResponse() - client.list_environments(request) - - # Establish that the 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_environments_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.ListEnvironmentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse()) - await client.list_environments(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_environments_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListEnvironmentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_environments( - 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_environments_flattened_error(): - client = EnvironmentsClient( - 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_environments( - environments.ListEnvironmentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_environments_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListEnvironmentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_environments( - 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_environments_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_environments( - environments.ListEnvironmentsRequest(), - parent='parent_value', - ) - - -def test_list_environments_pager(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_environments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - environments.Environment(), - ], - next_page_token='abc', - ), - environments.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - ], - next_page_token='ghi', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_environments(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, environments.Environment) - for i in results) -def test_list_environments_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_environments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - environments.Environment(), - ], - next_page_token='abc', - ), - environments.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - ], - next_page_token='ghi', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_environments(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_environments_async_pager(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - environments.Environment(), - ], - next_page_token='abc', - ), - environments.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - ], - next_page_token='ghi', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_environments(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, environments.Environment) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_environments_async_pages(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - environments.Environment(), - ], - next_page_token='abc', - ), - environments.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - ], - next_page_token='ghi', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - ], - ), - 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_environments(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", [ - environments.UpdateEnvironmentRequest, - dict, -]) -def test_update_environment(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.UpdateEnvironmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_environment_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 = EnvironmentsClient( - 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 = environments.UpdateEnvironmentRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_environment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateEnvironmentRequest( - name='name_value', - ) - -def test_update_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - request = {} - client.update_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( - 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_environment 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_environment] = mock_rpc - - request = {} - await client.update_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateEnvironmentRequest): - client = EnvironmentsAsyncClient( - 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_environment), - '__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_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.UpdateEnvironmentRequest() - 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_environment_async_from_dict(): - await test_update_environment_async(request_type=dict) - -def test_update_environment_field_headers(): - client = EnvironmentsClient( - 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 = environments.UpdateEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.UpdateEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_update_environment_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__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_environment( - name='name_value', - environment=environments.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].environment - mock_val = environments.Environment(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_environment_flattened_error(): - client = EnvironmentsClient( - 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_environment( - environments.UpdateEnvironmentRequest(), - name='name_value', - environment=environments.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_environment_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__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_environment( - name='name_value', - environment=environments.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].environment - mock_val = environments.Environment(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_environment_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_environment( - environments.UpdateEnvironmentRequest(), - name='name_value', - environment=environments.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteEnvironmentRequest, - dict, -]) -def test_delete_environment(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.DeleteEnvironmentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_environment_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 = EnvironmentsClient( - 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 = environments.DeleteEnvironmentRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_environment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteEnvironmentRequest( - name='name_value', - ) - -def test_delete_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - request = {} - client.delete_environment(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_environment(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_environment_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 = EnvironmentsAsyncClient( - 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_environment 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_environment] = mock_rpc - - request = {} - await client.delete_environment(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_environment(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_environment_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteEnvironmentRequest): - client = EnvironmentsAsyncClient( - 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_environment), - '__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_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.DeleteEnvironmentRequest() - 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_environment_async_from_dict(): - await test_delete_environment_async(request_type=dict) - -def test_delete_environment_field_headers(): - client = EnvironmentsClient( - 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 = environments.DeleteEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_environment(request) - - # Establish that the 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_environment_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.DeleteEnvironmentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_environment(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_environment_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__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_environment( - 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_environment_flattened_error(): - client = EnvironmentsClient( - 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_environment( - environments.DeleteEnvironmentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_environment_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__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_environment( - 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_environment_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_environment( - environments.DeleteEnvironmentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.RestartWebServerRequest, - dict, -]) -def test_restart_web_server(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.restart_web_server), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.restart_web_server(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.RestartWebServerRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_restart_web_server_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 = EnvironmentsClient( - 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 = environments.RestartWebServerRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restart_web_server), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.restart_web_server(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.RestartWebServerRequest( - name='name_value', - ) - -def test_restart_web_server_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 = EnvironmentsClient( - 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.restart_web_server 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.restart_web_server] = mock_rpc - request = {} - client.restart_web_server(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.restart_web_server(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_restart_web_server_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 = EnvironmentsAsyncClient( - 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.restart_web_server 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.restart_web_server] = mock_rpc - - request = {} - await client.restart_web_server(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.restart_web_server(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_restart_web_server_async(transport: str = 'grpc_asyncio', request_type=environments.RestartWebServerRequest): - client = EnvironmentsAsyncClient( - 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.restart_web_server), - '__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.restart_web_server(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.RestartWebServerRequest() - 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_restart_web_server_async_from_dict(): - await test_restart_web_server_async(request_type=dict) - -def test_restart_web_server_field_headers(): - client = EnvironmentsClient( - 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 = environments.RestartWebServerRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restart_web_server), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.restart_web_server(request) - - # Establish that the 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_restart_web_server_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.RestartWebServerRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restart_web_server), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.restart_web_server(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.CheckUpgradeRequest, - dict, -]) -def test_check_upgrade(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.check_upgrade), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.check_upgrade(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.CheckUpgradeRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_check_upgrade_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 = EnvironmentsClient( - 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 = environments.CheckUpgradeRequest( - environment='environment_value', - image_version='image_version_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.check_upgrade(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CheckUpgradeRequest( - environment='environment_value', - image_version='image_version_value', - ) - -def test_check_upgrade_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 = EnvironmentsClient( - 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.check_upgrade 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.check_upgrade] = mock_rpc - request = {} - client.check_upgrade(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.check_upgrade(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_check_upgrade_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 = EnvironmentsAsyncClient( - 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.check_upgrade 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.check_upgrade] = mock_rpc - - request = {} - await client.check_upgrade(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.check_upgrade(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_check_upgrade_async(transport: str = 'grpc_asyncio', request_type=environments.CheckUpgradeRequest): - client = EnvironmentsAsyncClient( - 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.check_upgrade), - '__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.check_upgrade(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.CheckUpgradeRequest() - 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_check_upgrade_async_from_dict(): - await test_check_upgrade_async(request_type=dict) - -def test_check_upgrade_field_headers(): - client = EnvironmentsClient( - 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 = environments.CheckUpgradeRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.check_upgrade(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_check_upgrade_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.CheckUpgradeRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.check_upgrade(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.ExecuteAirflowCommandRequest, - dict, -]) -def test_execute_airflow_command(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.execute_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ExecuteAirflowCommandResponse( - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - error='error_value', - ) - response = client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.ExecuteAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.ExecuteAirflowCommandResponse) - assert response.execution_id == 'execution_id_value' - assert response.pod == 'pod_value' - assert response.pod_namespace == 'pod_namespace_value' - assert response.error == 'error_value' - - -def test_execute_airflow_command_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 = EnvironmentsClient( - 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 = environments.ExecuteAirflowCommandRequest( - environment='environment_value', - command='command_value', - subcommand='subcommand_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.execute_airflow_command(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ExecuteAirflowCommandRequest( - environment='environment_value', - command='command_value', - subcommand='subcommand_value', - ) - -def test_execute_airflow_command_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 = EnvironmentsClient( - 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc - request = {} - client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.execute_airflow_command(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_execute_airflow_command_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 = EnvironmentsAsyncClient( - 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc - - request = {} - await client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.execute_airflow_command(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_execute_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.ExecuteAirflowCommandRequest): - client = EnvironmentsAsyncClient( - 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.execute_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse( - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - error='error_value', - )) - response = await client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.ExecuteAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.ExecuteAirflowCommandResponse) - assert response.execution_id == 'execution_id_value' - assert response.pod == 'pod_value' - assert response.pod_namespace == 'pod_namespace_value' - assert response.error == 'error_value' - - -@pytest.mark.asyncio -async def test_execute_airflow_command_async_from_dict(): - await test_execute_airflow_command_async(request_type=dict) - -def test_execute_airflow_command_field_headers(): - client = EnvironmentsClient( - 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 = environments.ExecuteAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - call.return_value = environments.ExecuteAirflowCommandResponse() - client.execute_airflow_command(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_execute_airflow_command_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.ExecuteAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse()) - await client.execute_airflow_command(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.StopAirflowCommandRequest, - dict, -]) -def test_stop_airflow_command(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.stop_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.StopAirflowCommandResponse( - is_done=True, - output=['output_value'], - ) - response = client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.StopAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.StopAirflowCommandResponse) - assert response.is_done is True - assert response.output == ['output_value'] - - -def test_stop_airflow_command_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 = EnvironmentsClient( - 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 = environments.StopAirflowCommandRequest( - environment='environment_value', - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.stop_airflow_command(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.StopAirflowCommandRequest( - environment='environment_value', - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - ) - -def test_stop_airflow_command_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 = EnvironmentsClient( - 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc - request = {} - client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stop_airflow_command(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_stop_airflow_command_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 = EnvironmentsAsyncClient( - 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc - - request = {} - await client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.stop_airflow_command(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_stop_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.StopAirflowCommandRequest): - client = EnvironmentsAsyncClient( - 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.stop_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse( - is_done=True, - output=['output_value'], - )) - response = await client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.StopAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.StopAirflowCommandResponse) - assert response.is_done is True - assert response.output == ['output_value'] - - -@pytest.mark.asyncio -async def test_stop_airflow_command_async_from_dict(): - await test_stop_airflow_command_async(request_type=dict) - -def test_stop_airflow_command_field_headers(): - client = EnvironmentsClient( - 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 = environments.StopAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - call.return_value = environments.StopAirflowCommandResponse() - client.stop_airflow_command(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_stop_airflow_command_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.StopAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse()) - await client.stop_airflow_command(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.PollAirflowCommandRequest, - dict, -]) -def test_poll_airflow_command(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.poll_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.PollAirflowCommandResponse( - output_end=True, - ) - response = client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.PollAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.PollAirflowCommandResponse) - assert response.output_end is True - - -def test_poll_airflow_command_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 = EnvironmentsClient( - 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 = environments.PollAirflowCommandRequest( - environment='environment_value', - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.poll_airflow_command(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.PollAirflowCommandRequest( - environment='environment_value', - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - ) - -def test_poll_airflow_command_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 = EnvironmentsClient( - 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc - request = {} - client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.poll_airflow_command(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_poll_airflow_command_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 = EnvironmentsAsyncClient( - 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc - - request = {} - await client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.poll_airflow_command(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_poll_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.PollAirflowCommandRequest): - client = EnvironmentsAsyncClient( - 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.poll_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse( - output_end=True, - )) - response = await client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.PollAirflowCommandRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.PollAirflowCommandResponse) - assert response.output_end is True - - -@pytest.mark.asyncio -async def test_poll_airflow_command_async_from_dict(): - await test_poll_airflow_command_async(request_type=dict) - -def test_poll_airflow_command_field_headers(): - client = EnvironmentsClient( - 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 = environments.PollAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - call.return_value = environments.PollAirflowCommandResponse() - client.poll_airflow_command(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_poll_airflow_command_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.PollAirflowCommandRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse()) - await client.poll_airflow_command(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.ListWorkloadsRequest, - dict, -]) -def test_list_workloads(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_workloads), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListWorkloadsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.ListWorkloadsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkloadsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_workloads_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 = EnvironmentsClient( - 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 = environments.ListWorkloadsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workloads(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListWorkloadsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_workloads_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 = EnvironmentsClient( - 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_workloads 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_workloads] = mock_rpc - request = {} - client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workloads(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_workloads_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 = EnvironmentsAsyncClient( - 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_workloads 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_workloads] = mock_rpc - - request = {} - await client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_workloads(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_workloads_async(transport: str = 'grpc_asyncio', request_type=environments.ListWorkloadsRequest): - client = EnvironmentsAsyncClient( - 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_workloads), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.ListWorkloadsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkloadsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_workloads_async_from_dict(): - await test_list_workloads_async(request_type=dict) - -def test_list_workloads_field_headers(): - client = EnvironmentsClient( - 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 = environments.ListWorkloadsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - call.return_value = environments.ListWorkloadsResponse() - client.list_workloads(request) - - # Establish that the 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_workloads_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.ListWorkloadsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse()) - await client.list_workloads(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_workloads_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListWorkloadsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_workloads( - 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_workloads_flattened_error(): - client = EnvironmentsClient( - 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_workloads( - environments.ListWorkloadsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_workloads_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListWorkloadsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_workloads( - 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_workloads_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_workloads( - environments.ListWorkloadsRequest(), - parent='parent_value', - ) - - -def test_list_workloads_pager(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_workloads), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='abc', - ), - environments.ListWorkloadsResponse( - workloads=[], - next_page_token='def', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='ghi', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workloads(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, environments.ListWorkloadsResponse.ComposerWorkload) - for i in results) -def test_list_workloads_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_workloads), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='abc', - ), - environments.ListWorkloadsResponse( - workloads=[], - next_page_token='def', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='ghi', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - ), - RuntimeError, - ) - pages = list(client.list_workloads(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_workloads_async_pager(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='abc', - ), - environments.ListWorkloadsResponse( - workloads=[], - next_page_token='def', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='ghi', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_workloads(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, environments.ListWorkloadsResponse.ComposerWorkload) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_workloads_async_pages(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='abc', - ), - environments.ListWorkloadsResponse( - workloads=[], - next_page_token='def', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='ghi', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - ), - 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_workloads(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", [ - environments.CreateUserWorkloadsSecretRequest, - dict, -]) -def test_create_user_workloads_secret(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret( - name='name_value', - ) - response = client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.CreateUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -def test_create_user_workloads_secret_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 = EnvironmentsClient( - 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 = environments.CreateUserWorkloadsSecretRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_user_workloads_secret(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsSecretRequest( - parent='parent_value', - ) - -def test_create_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - request = {} - client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - await client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.CreateUserWorkloadsSecretRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - response = await client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.CreateUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_user_workloads_secret_async_from_dict(): - await test_create_user_workloads_secret_async(request_type=dict) - -def test_create_user_workloads_secret_field_headers(): - client = EnvironmentsClient( - 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 = environments.CreateUserWorkloadsSecretRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.create_user_workloads_secret(request) - - # Establish that the 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_user_workloads_secret_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.CreateUserWorkloadsSecretRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - await client.create_user_workloads_secret(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_user_workloads_secret_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_user_workloads_secret( - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].user_workloads_secret - mock_val = environments.UserWorkloadsSecret(name='name_value') - assert arg == mock_val - - -def test_create_user_workloads_secret_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.CreateUserWorkloadsSecretRequest(), - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_user_workloads_secret_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_user_workloads_secret( - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].user_workloads_secret - mock_val = environments.UserWorkloadsSecret(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_user_workloads_secret_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret( - environments.CreateUserWorkloadsSecretRequest(), - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsSecretRequest, - dict, -]) -def test_get_user_workloads_secret(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret( - name='name_value', - ) - response = client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.GetUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -def test_get_user_workloads_secret_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 = EnvironmentsClient( - 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 = environments.GetUserWorkloadsSecretRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_user_workloads_secret(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsSecretRequest( - name='name_value', - ) - -def test_get_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - request = {} - client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - await client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.GetUserWorkloadsSecretRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - response = await client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.GetUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_user_workloads_secret_async_from_dict(): - await test_get_user_workloads_secret_async(request_type=dict) - -def test_get_user_workloads_secret_field_headers(): - client = EnvironmentsClient( - 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 = environments.GetUserWorkloadsSecretRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.get_user_workloads_secret(request) - - # Establish that the 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_user_workloads_secret_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.GetUserWorkloadsSecretRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - await client.get_user_workloads_secret(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_user_workloads_secret_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_user_workloads_secret( - 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_user_workloads_secret_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.GetUserWorkloadsSecretRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_user_workloads_secret_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_user_workloads_secret( - 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_user_workloads_secret_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret( - environments.GetUserWorkloadsSecretRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsSecretsRequest, - dict, -]) -def test_list_user_workloads_secrets(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_secrets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsSecretsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.ListUserWorkloadsSecretsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsSecretsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_user_workloads_secrets_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 = EnvironmentsClient( - 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 = environments.ListUserWorkloadsSecretsRequest( - 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_user_workloads_secrets), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_user_workloads_secrets(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsSecretsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_user_workloads_secrets_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 = EnvironmentsClient( - 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc - request = {} - client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_user_workloads_secrets(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_user_workloads_secrets_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 = EnvironmentsAsyncClient( - 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc - - request = {} - await client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_user_workloads_secrets(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_user_workloads_secrets_async(transport: str = 'grpc_asyncio', request_type=environments.ListUserWorkloadsSecretsRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_secrets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.ListUserWorkloadsSecretsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsSecretsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_user_workloads_secrets_async_from_dict(): - await test_list_user_workloads_secrets_async(request_type=dict) - -def test_list_user_workloads_secrets_field_headers(): - client = EnvironmentsClient( - 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 = environments.ListUserWorkloadsSecretsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - call.return_value = environments.ListUserWorkloadsSecretsResponse() - client.list_user_workloads_secrets(request) - - # Establish that the 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_user_workloads_secrets_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.ListUserWorkloadsSecretsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse()) - await client.list_user_workloads_secrets(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_user_workloads_secrets_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsSecretsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_user_workloads_secrets( - 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_user_workloads_secrets_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_secrets( - environments.ListUserWorkloadsSecretsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_user_workloads_secrets_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsSecretsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_user_workloads_secrets( - 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_user_workloads_secrets_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_secrets( - environments.ListUserWorkloadsSecretsRequest(), - parent='parent_value', - ) - - -def test_list_user_workloads_secrets_pager(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_user_workloads_secrets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[], - next_page_token='def', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_user_workloads_secrets(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, environments.UserWorkloadsSecret) - for i in results) -def test_list_user_workloads_secrets_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_user_workloads_secrets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[], - next_page_token='def', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - ), - RuntimeError, - ) - pages = list(client.list_user_workloads_secrets(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_user_workloads_secrets_async_pager(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[], - next_page_token='def', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_user_workloads_secrets(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, environments.UserWorkloadsSecret) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_user_workloads_secrets_async_pages(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[], - next_page_token='def', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - ), - 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_user_workloads_secrets(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", [ - environments.UpdateUserWorkloadsSecretRequest, - dict, -]) -def test_update_user_workloads_secret(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret( - name='name_value', - ) - response = client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.UpdateUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -def test_update_user_workloads_secret_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 = EnvironmentsClient( - 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 = environments.UpdateUserWorkloadsSecretRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_user_workloads_secret(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsSecretRequest( - ) - -def test_update_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - request = {} - client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - await client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateUserWorkloadsSecretRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - response = await client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.UpdateUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_user_workloads_secret_async_from_dict(): - await test_update_user_workloads_secret_async(request_type=dict) - -def test_update_user_workloads_secret_field_headers(): - client = EnvironmentsClient( - 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 = environments.UpdateUserWorkloadsSecretRequest() - - request.user_workloads_secret.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.update_user_workloads_secret(request) - - # Establish that the 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', - 'user_workloads_secret.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_user_workloads_secret_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.UpdateUserWorkloadsSecretRequest() - - request.user_workloads_secret.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - await client.update_user_workloads_secret(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', - 'user_workloads_secret.name=name_value', - ) in kw['metadata'] - - -def test_update_user_workloads_secret_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_user_workloads_secret( - user_workloads_secret=environments.UserWorkloadsSecret(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].user_workloads_secret - mock_val = environments.UserWorkloadsSecret(name='name_value') - assert arg == mock_val - - -def test_update_user_workloads_secret_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.UpdateUserWorkloadsSecretRequest(), - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_user_workloads_secret_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsSecret() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_user_workloads_secret( - user_workloads_secret=environments.UserWorkloadsSecret(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].user_workloads_secret - mock_val = environments.UserWorkloadsSecret(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_user_workloads_secret_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret( - environments.UpdateUserWorkloadsSecretRequest(), - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsSecretRequest, - dict, -]) -def test_delete_user_workloads_secret(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.DeleteUserWorkloadsSecretRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_user_workloads_secret_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 = EnvironmentsClient( - 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 = environments.DeleteUserWorkloadsSecretRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_user_workloads_secret(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsSecretRequest( - name='name_value', - ) - -def test_delete_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - request = {} - client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user_workloads_secret(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_user_workloads_secret_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 = EnvironmentsAsyncClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - await client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_user_workloads_secret(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_user_workloads_secret_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteUserWorkloadsSecretRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.DeleteUserWorkloadsSecretRequest() - 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_user_workloads_secret_async_from_dict(): - await test_delete_user_workloads_secret_async(request_type=dict) - -def test_delete_user_workloads_secret_field_headers(): - client = EnvironmentsClient( - 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 = environments.DeleteUserWorkloadsSecretRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - call.return_value = None - client.delete_user_workloads_secret(request) - - # Establish that the 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_user_workloads_secret_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.DeleteUserWorkloadsSecretRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user_workloads_secret(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_user_workloads_secret_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_user_workloads_secret( - 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_user_workloads_secret_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.DeleteUserWorkloadsSecretRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_user_workloads_secret_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_user_workloads_secret( - 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_user_workloads_secret_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_secret( - environments.DeleteUserWorkloadsSecretRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsConfigMapRequest, - dict, -]) -def test_create_user_workloads_config_map(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap( - name='name_value', - ) - response = client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.CreateUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -def test_create_user_workloads_config_map_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 = EnvironmentsClient( - 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 = environments.CreateUserWorkloadsConfigMapRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_user_workloads_config_map(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsConfigMapRequest( - parent='parent_value', - ) - -def test_create_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - request = {} - client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - await client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.CreateUserWorkloadsConfigMapRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - response = await client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.CreateUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_user_workloads_config_map_async_from_dict(): - await test_create_user_workloads_config_map_async(request_type=dict) - -def test_create_user_workloads_config_map_field_headers(): - client = EnvironmentsClient( - 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 = environments.CreateUserWorkloadsConfigMapRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.create_user_workloads_config_map(request) - - # Establish that the 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_user_workloads_config_map_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.CreateUserWorkloadsConfigMapRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - await client.create_user_workloads_config_map(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_user_workloads_config_map_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_user_workloads_config_map( - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].user_workloads_config_map - mock_val = environments.UserWorkloadsConfigMap(name='name_value') - assert arg == mock_val - - -def test_create_user_workloads_config_map_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.CreateUserWorkloadsConfigMapRequest(), - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_user_workloads_config_map_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_user_workloads_config_map( - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].user_workloads_config_map - mock_val = environments.UserWorkloadsConfigMap(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_user_workloads_config_map_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map( - environments.CreateUserWorkloadsConfigMapRequest(), - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsConfigMapRequest, - dict, -]) -def test_get_user_workloads_config_map(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap( - name='name_value', - ) - response = client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.GetUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -def test_get_user_workloads_config_map_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 = EnvironmentsClient( - 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 = environments.GetUserWorkloadsConfigMapRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_user_workloads_config_map(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsConfigMapRequest( - name='name_value', - ) - -def test_get_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - request = {} - client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - await client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.GetUserWorkloadsConfigMapRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - response = await client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.GetUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_user_workloads_config_map_async_from_dict(): - await test_get_user_workloads_config_map_async(request_type=dict) - -def test_get_user_workloads_config_map_field_headers(): - client = EnvironmentsClient( - 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 = environments.GetUserWorkloadsConfigMapRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.get_user_workloads_config_map(request) - - # Establish that the 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_user_workloads_config_map_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.GetUserWorkloadsConfigMapRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - await client.get_user_workloads_config_map(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_user_workloads_config_map_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_user_workloads_config_map( - 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_user_workloads_config_map_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.GetUserWorkloadsConfigMapRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_user_workloads_config_map_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_user_workloads_config_map( - 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_user_workloads_config_map_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map( - environments.GetUserWorkloadsConfigMapRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsConfigMapsRequest, - dict, -]) -def test_list_user_workloads_config_maps(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_config_maps), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsConfigMapsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.ListUserWorkloadsConfigMapsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsConfigMapsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_user_workloads_config_maps_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 = EnvironmentsClient( - 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 = environments.ListUserWorkloadsConfigMapsRequest( - 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_user_workloads_config_maps), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_user_workloads_config_maps(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsConfigMapsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_user_workloads_config_maps_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 = EnvironmentsClient( - 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc - request = {} - client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_user_workloads_config_maps(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_user_workloads_config_maps_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 = EnvironmentsAsyncClient( - 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc - - request = {} - await client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_user_workloads_config_maps(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_user_workloads_config_maps_async(transport: str = 'grpc_asyncio', request_type=environments.ListUserWorkloadsConfigMapsRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_maps), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.ListUserWorkloadsConfigMapsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsConfigMapsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_user_workloads_config_maps_async_from_dict(): - await test_list_user_workloads_config_maps_async(request_type=dict) - -def test_list_user_workloads_config_maps_field_headers(): - client = EnvironmentsClient( - 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 = environments.ListUserWorkloadsConfigMapsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - call.return_value = environments.ListUserWorkloadsConfigMapsResponse() - client.list_user_workloads_config_maps(request) - - # Establish that the 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_user_workloads_config_maps_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.ListUserWorkloadsConfigMapsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse()) - await client.list_user_workloads_config_maps(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_user_workloads_config_maps_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsConfigMapsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_user_workloads_config_maps( - 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_user_workloads_config_maps_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_config_maps( - environments.ListUserWorkloadsConfigMapsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_user_workloads_config_maps_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.ListUserWorkloadsConfigMapsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_user_workloads_config_maps( - 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_user_workloads_config_maps_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_maps( - environments.ListUserWorkloadsConfigMapsRequest(), - parent='parent_value', - ) - - -def test_list_user_workloads_config_maps_pager(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_user_workloads_config_maps), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[], - next_page_token='def', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_user_workloads_config_maps(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, environments.UserWorkloadsConfigMap) - for i in results) -def test_list_user_workloads_config_maps_pages(transport_name: str = "grpc"): - client = EnvironmentsClient( - 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_user_workloads_config_maps), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[], - next_page_token='def', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - ), - RuntimeError, - ) - pages = list(client.list_user_workloads_config_maps(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_user_workloads_config_maps_async_pager(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[], - next_page_token='def', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_user_workloads_config_maps(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, environments.UserWorkloadsConfigMap) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_user_workloads_config_maps_async_pages(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[], - next_page_token='def', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - ), - 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_user_workloads_config_maps(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", [ - environments.UpdateUserWorkloadsConfigMapRequest, - dict, -]) -def test_update_user_workloads_config_map(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap( - name='name_value', - ) - response = client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.UpdateUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -def test_update_user_workloads_config_map_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 = EnvironmentsClient( - 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 = environments.UpdateUserWorkloadsConfigMapRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_user_workloads_config_map(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest( - ) - -def test_update_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - request = {} - client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - await client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateUserWorkloadsConfigMapRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - response = await client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.UpdateUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_user_workloads_config_map_async_from_dict(): - await test_update_user_workloads_config_map_async(request_type=dict) - -def test_update_user_workloads_config_map_field_headers(): - client = EnvironmentsClient( - 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 = environments.UpdateUserWorkloadsConfigMapRequest() - - request.user_workloads_config_map.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.update_user_workloads_config_map(request) - - # Establish that the 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', - 'user_workloads_config_map.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_user_workloads_config_map_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.UpdateUserWorkloadsConfigMapRequest() - - request.user_workloads_config_map.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - await client.update_user_workloads_config_map(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', - 'user_workloads_config_map.name=name_value', - ) in kw['metadata'] - - -def test_update_user_workloads_config_map_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_user_workloads_config_map( - user_workloads_config_map=environments.UserWorkloadsConfigMap(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].user_workloads_config_map - mock_val = environments.UserWorkloadsConfigMap(name='name_value') - assert arg == mock_val - - -def test_update_user_workloads_config_map_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.UpdateUserWorkloadsConfigMapRequest(), - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_user_workloads_config_map_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.UserWorkloadsConfigMap() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_user_workloads_config_map( - user_workloads_config_map=environments.UserWorkloadsConfigMap(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].user_workloads_config_map - mock_val = environments.UserWorkloadsConfigMap(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_user_workloads_config_map_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map( - environments.UpdateUserWorkloadsConfigMapRequest(), - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsConfigMapRequest, - dict, -]) -def test_delete_user_workloads_config_map(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.DeleteUserWorkloadsConfigMapRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_user_workloads_config_map_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 = EnvironmentsClient( - 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 = environments.DeleteUserWorkloadsConfigMapRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_user_workloads_config_map(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest( - name='name_value', - ) - -def test_delete_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - request = {} - client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user_workloads_config_map(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_user_workloads_config_map_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 = EnvironmentsAsyncClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - await client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_user_workloads_config_map(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_user_workloads_config_map_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteUserWorkloadsConfigMapRequest): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.DeleteUserWorkloadsConfigMapRequest() - 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_user_workloads_config_map_async_from_dict(): - await test_delete_user_workloads_config_map_async(request_type=dict) - -def test_delete_user_workloads_config_map_field_headers(): - client = EnvironmentsClient( - 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 = environments.DeleteUserWorkloadsConfigMapRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - call.return_value = None - client.delete_user_workloads_config_map(request) - - # Establish that the 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_user_workloads_config_map_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.DeleteUserWorkloadsConfigMapRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user_workloads_config_map(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_user_workloads_config_map_flattened(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_user_workloads_config_map( - 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_user_workloads_config_map_flattened_error(): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.DeleteUserWorkloadsConfigMapRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_user_workloads_config_map_flattened_async(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_user_workloads_config_map( - 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_user_workloads_config_map_flattened_error_async(): - client = EnvironmentsAsyncClient( - 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_user_workloads_config_map( - environments.DeleteUserWorkloadsConfigMapRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - environments.SaveSnapshotRequest, - dict, -]) -def test_save_snapshot(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.save_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.save_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.SaveSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_save_snapshot_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 = EnvironmentsClient( - 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 = environments.SaveSnapshotRequest( - environment='environment_value', - snapshot_location='snapshot_location_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.save_snapshot(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.SaveSnapshotRequest( - environment='environment_value', - snapshot_location='snapshot_location_value', - ) - -def test_save_snapshot_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 = EnvironmentsClient( - 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.save_snapshot 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.save_snapshot] = mock_rpc - request = {} - client.save_snapshot(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.save_snapshot(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_save_snapshot_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 = EnvironmentsAsyncClient( - 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.save_snapshot 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.save_snapshot] = mock_rpc - - request = {} - await client.save_snapshot(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.save_snapshot(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_save_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.SaveSnapshotRequest): - client = EnvironmentsAsyncClient( - 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.save_snapshot), - '__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.save_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.SaveSnapshotRequest() - 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_save_snapshot_async_from_dict(): - await test_save_snapshot_async(request_type=dict) - -def test_save_snapshot_field_headers(): - client = EnvironmentsClient( - 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 = environments.SaveSnapshotRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.save_snapshot(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_save_snapshot_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.SaveSnapshotRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.save_snapshot(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.LoadSnapshotRequest, - dict, -]) -def test_load_snapshot(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.load_snapshot), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.load_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.LoadSnapshotRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_load_snapshot_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 = EnvironmentsClient( - 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 = environments.LoadSnapshotRequest( - environment='environment_value', - snapshot_path='snapshot_path_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.load_snapshot(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.LoadSnapshotRequest( - environment='environment_value', - snapshot_path='snapshot_path_value', - ) - -def test_load_snapshot_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 = EnvironmentsClient( - 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.load_snapshot 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.load_snapshot] = mock_rpc - request = {} - client.load_snapshot(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.load_snapshot(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_load_snapshot_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 = EnvironmentsAsyncClient( - 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.load_snapshot 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.load_snapshot] = mock_rpc - - request = {} - await client.load_snapshot(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.load_snapshot(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_load_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.LoadSnapshotRequest): - client = EnvironmentsAsyncClient( - 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.load_snapshot), - '__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.load_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.LoadSnapshotRequest() - 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_load_snapshot_async_from_dict(): - await test_load_snapshot_async(request_type=dict) - -def test_load_snapshot_field_headers(): - client = EnvironmentsClient( - 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 = environments.LoadSnapshotRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.load_snapshot(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_load_snapshot_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.LoadSnapshotRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.load_snapshot(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.DatabaseFailoverRequest, - dict, -]) -def test_database_failover(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.database_failover), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.database_failover(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.DatabaseFailoverRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_database_failover_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 = EnvironmentsClient( - 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 = environments.DatabaseFailoverRequest( - environment='environment_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.database_failover(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DatabaseFailoverRequest( - environment='environment_value', - ) - -def test_database_failover_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 = EnvironmentsClient( - 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.database_failover 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.database_failover] = mock_rpc - request = {} - client.database_failover(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.database_failover(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_database_failover_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 = EnvironmentsAsyncClient( - 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.database_failover 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.database_failover] = mock_rpc - - request = {} - await client.database_failover(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.database_failover(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_database_failover_async(transport: str = 'grpc_asyncio', request_type=environments.DatabaseFailoverRequest): - client = EnvironmentsAsyncClient( - 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.database_failover), - '__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.database_failover(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.DatabaseFailoverRequest() - 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_database_failover_async_from_dict(): - await test_database_failover_async(request_type=dict) - -def test_database_failover_field_headers(): - client = EnvironmentsClient( - 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 = environments.DatabaseFailoverRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.database_failover(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_database_failover_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.DatabaseFailoverRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.database_failover(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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - environments.FetchDatabasePropertiesRequest, - dict, -]) -def test_fetch_database_properties(request_type, transport: str = 'grpc'): - client = EnvironmentsClient( - 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.fetch_database_properties), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = environments.FetchDatabasePropertiesResponse( - primary_gce_zone='primary_gce_zone_value', - secondary_gce_zone='secondary_gce_zone_value', - is_failover_replica_available=True, - ) - response = client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = environments.FetchDatabasePropertiesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.FetchDatabasePropertiesResponse) - assert response.primary_gce_zone == 'primary_gce_zone_value' - assert response.secondary_gce_zone == 'secondary_gce_zone_value' - assert response.is_failover_replica_available is True - - -def test_fetch_database_properties_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 = EnvironmentsClient( - 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 = environments.FetchDatabasePropertiesRequest( - environment='environment_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.fetch_database_properties(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.FetchDatabasePropertiesRequest( - environment='environment_value', - ) - -def test_fetch_database_properties_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 = EnvironmentsClient( - 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc - request = {} - client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_database_properties(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_fetch_database_properties_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 = EnvironmentsAsyncClient( - 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc - - request = {} - await client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.fetch_database_properties(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_fetch_database_properties_async(transport: str = 'grpc_asyncio', request_type=environments.FetchDatabasePropertiesRequest): - client = EnvironmentsAsyncClient( - 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.fetch_database_properties), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse( - primary_gce_zone='primary_gce_zone_value', - secondary_gce_zone='secondary_gce_zone_value', - is_failover_replica_available=True, - )) - response = await client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = environments.FetchDatabasePropertiesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.FetchDatabasePropertiesResponse) - assert response.primary_gce_zone == 'primary_gce_zone_value' - assert response.secondary_gce_zone == 'secondary_gce_zone_value' - assert response.is_failover_replica_available is True - - -@pytest.mark.asyncio -async def test_fetch_database_properties_async_from_dict(): - await test_fetch_database_properties_async(request_type=dict) - -def test_fetch_database_properties_field_headers(): - client = EnvironmentsClient( - 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 = environments.FetchDatabasePropertiesRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - call.return_value = environments.FetchDatabasePropertiesResponse() - client.fetch_database_properties(request) - - # Establish that the 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', - 'environment=environment_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_fetch_database_properties_field_headers_async(): - client = EnvironmentsAsyncClient( - 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 = environments.FetchDatabasePropertiesRequest() - - request.environment = 'environment_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse()) - await client.fetch_database_properties(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', - 'environment=environment_value', - ) in kw['metadata'] - - -def test_create_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - - request = {} - client.create_environment(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_environment(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_environment_rest_flattened(): - client = EnvironmentsClient( - 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', - environment=environments.Environment(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.create_environment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*}/environments" % client.transport._host, args[1]) - - -def test_create_environment_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_environment( - environments.CreateEnvironmentRequest(), - parent='parent_value', - environment=environments.Environment(name='name_value'), - ) - - -def test_get_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - - request = {} - client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_environment(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_environment_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.Environment() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/environments/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 = environments.Environment.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_environment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*}" % client.transport._host, args[1]) - - -def test_get_environment_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_environment( - environments.GetEnvironmentRequest(), - name='name_value', - ) - - -def test_list_environments_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 = EnvironmentsClient( - 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_environments 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_environments] = mock_rpc - - request = {} - client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_environments(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_environments_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.ListEnvironmentsResponse() - - # 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 = environments.ListEnvironmentsResponse.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_environments(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*}/environments" % client.transport._host, args[1]) - - -def test_list_environments_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_environments( - environments.ListEnvironmentsRequest(), - parent='parent_value', - ) - - -def test_list_environments_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - 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 = ( - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - environments.Environment(), - ], - next_page_token='abc', - ), - environments.ListEnvironmentsResponse( - environments=[], - next_page_token='def', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - ], - next_page_token='ghi', - ), - environments.ListEnvironmentsResponse( - environments=[ - environments.Environment(), - environments.Environment(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environments.ListEnvironmentsResponse.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_environments(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environments.Environment) - for i in results) - - pages = list(client.list_environments(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_update_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - - request = {} - client.update_environment(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_environment(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_environment_rest_required_fields(request_type=environments.UpdateEnvironmentRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_environment._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_environment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = EnvironmentsClient( - 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_environment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_environment_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_environment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) - - -def test_update_environment_rest_flattened(): - client = EnvironmentsClient( - 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/environments/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - environment=environments.Environment(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_environment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*}" % client.transport._host, args[1]) - - -def test_update_environment_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_environment( - environments.UpdateEnvironmentRequest(), - name='name_value', - environment=environments.Environment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_environment_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 = EnvironmentsClient( - 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_environment 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_environment] = mock_rpc - - request = {} - client.delete_environment(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_environment(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_environment_rest_flattened(): - client = EnvironmentsClient( - 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/environments/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_environment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*}" % client.transport._host, args[1]) - - -def test_delete_environment_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_environment( - environments.DeleteEnvironmentRequest(), - name='name_value', - ) - - -def test_restart_web_server_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 = EnvironmentsClient( - 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.restart_web_server 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.restart_web_server] = mock_rpc - - request = {} - client.restart_web_server(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.restart_web_server(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_check_upgrade_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 = EnvironmentsClient( - 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.check_upgrade 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.check_upgrade] = mock_rpc - - request = {} - client.check_upgrade(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.check_upgrade(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_execute_airflow_command_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 = EnvironmentsClient( - 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.execute_airflow_command 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.execute_airflow_command] = mock_rpc - - request = {} - client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.execute_airflow_command(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_stop_airflow_command_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 = EnvironmentsClient( - 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.stop_airflow_command 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.stop_airflow_command] = mock_rpc - - request = {} - client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.stop_airflow_command(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_poll_airflow_command_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 = EnvironmentsClient( - 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.poll_airflow_command 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.poll_airflow_command] = mock_rpc - - request = {} - client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.poll_airflow_command(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_workloads_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 = EnvironmentsClient( - 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_workloads 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_workloads] = mock_rpc - - request = {} - client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_workloads(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_workloads_rest_required_fields(request_type=environments.ListWorkloadsRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_workloads._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_workloads._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.ListWorkloadsResponse() - # 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 = environments.ListWorkloadsResponse.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_workloads(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_workloads_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_workloads._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_workloads_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.ListWorkloadsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListWorkloadsResponse.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_workloads(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/environments/*}/workloads" % client.transport._host, args[1]) - - -def test_list_workloads_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_workloads( - environments.ListWorkloadsRequest(), - parent='parent_value', - ) - - -def test_list_workloads_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - 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 = ( - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='abc', - ), - environments.ListWorkloadsResponse( - workloads=[], - next_page_token='def', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - next_page_token='ghi', - ), - environments.ListWorkloadsResponse( - workloads=[ - environments.ListWorkloadsResponse.ComposerWorkload(), - environments.ListWorkloadsResponse.ComposerWorkload(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environments.ListWorkloadsResponse.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/environments/sample3'} - - pager = client.list_workloads(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environments.ListWorkloadsResponse.ComposerWorkload) - for i in results) - - pages = list(client.list_workloads(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.CreateUserWorkloadsSecretRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_secret._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_secret._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.UserWorkloadsSecret() - # 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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_user_workloads_secret_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_user_workloads_secret._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "userWorkloadsSecret", ))) - - -def test_create_user_workloads_secret_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsSecret() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets" % client.transport._host, args[1]) - - -def test_create_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.CreateUserWorkloadsSecretRequest(), - parent='parent_value', - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - - -def test_get_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.GetUserWorkloadsSecretRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_secret._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_user_workloads_secret._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.UserWorkloadsSecret() - # 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 = environments.UserWorkloadsSecret.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_user_workloads_secret(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_user_workloads_secret_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_user_workloads_secret._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_user_workloads_secret_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsSecret() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = environments.UserWorkloadsSecret.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_user_workloads_secret(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) - - -def test_get_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.GetUserWorkloadsSecretRequest(), - name='name_value', - ) - - -def test_list_user_workloads_secrets_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 = EnvironmentsClient( - 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_user_workloads_secrets 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_user_workloads_secrets] = mock_rpc - - request = {} - client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_user_workloads_secrets(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_user_workloads_secrets_rest_required_fields(request_type=environments.ListUserWorkloadsSecretsRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_secrets._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_user_workloads_secrets._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.ListUserWorkloadsSecretsResponse() - # 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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_user_workloads_secrets_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_user_workloads_secrets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_user_workloads_secrets_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.ListUserWorkloadsSecretsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets" % client.transport._host, args[1]) - - -def test_list_user_workloads_secrets_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_secrets( - environments.ListUserWorkloadsSecretsRequest(), - parent='parent_value', - ) - - -def test_list_user_workloads_secrets_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - 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 = ( - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[], - next_page_token='def', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsSecretsResponse( - user_workloads_secrets=[ - environments.UserWorkloadsSecret(), - environments.UserWorkloadsSecret(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environments.ListUserWorkloadsSecretsResponse.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/environments/sample3'} - - pager = client.list_user_workloads_secrets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environments.UserWorkloadsSecret) - for i in results) - - pages = list(client.list_user_workloads_secrets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_update_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user_workloads_secret(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_user_workloads_secret_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsSecret() - - # get arguments that satisfy an http rule for this method - sample_request = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - user_workloads_secret=environments.UserWorkloadsSecret(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 = environments.UserWorkloadsSecret.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.update_user_workloads_secret(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) - - -def test_update_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.UpdateUserWorkloadsSecretRequest(), - user_workloads_secret=environments.UserWorkloadsSecret(name='name_value'), - ) - - -def test_delete_user_workloads_secret_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 = EnvironmentsClient( - 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_user_workloads_secret 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_user_workloads_secret] = mock_rpc - - request = {} - client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user_workloads_secret(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_user_workloads_secret_rest_required_fields(request_type=environments.DeleteUserWorkloadsSecretRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_secret._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_user_workloads_secret._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # 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 = '' - - response_value._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_user_workloads_secret(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_user_workloads_secret_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_user_workloads_secret._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_user_workloads_secret_rest_flattened(): - client = EnvironmentsClient( - 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 = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = '' - response_value._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_user_workloads_secret(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}" % client.transport._host, args[1]) - - -def test_delete_user_workloads_secret_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_secret( - environments.DeleteUserWorkloadsSecretRequest(), - name='name_value', - ) - - -def test_create_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.CreateUserWorkloadsConfigMapRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_config_map._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user_workloads_config_map._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.UserWorkloadsConfigMap() - # 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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_user_workloads_config_map_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_user_workloads_config_map._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "userWorkloadsConfigMap", ))) - - -def test_create_user_workloads_config_map_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsConfigMap() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps" % client.transport._host, args[1]) - - -def test_create_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.CreateUserWorkloadsConfigMapRequest(), - parent='parent_value', - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - - -def test_get_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.GetUserWorkloadsConfigMapRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_config_map._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_user_workloads_config_map._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.UserWorkloadsConfigMap() - # 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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_user_workloads_config_map_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_user_workloads_config_map._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_user_workloads_config_map_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsConfigMap() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) - - -def test_get_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.GetUserWorkloadsConfigMapRequest(), - name='name_value', - ) - - -def test_list_user_workloads_config_maps_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 = EnvironmentsClient( - 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_user_workloads_config_maps 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_user_workloads_config_maps] = mock_rpc - - request = {} - client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_user_workloads_config_maps(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_user_workloads_config_maps_rest_required_fields(request_type=environments.ListUserWorkloadsConfigMapsRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_config_maps._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_user_workloads_config_maps._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.ListUserWorkloadsConfigMapsResponse() - # 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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_user_workloads_config_maps_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_user_workloads_config_maps._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_user_workloads_config_maps_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.ListUserWorkloadsConfigMapsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps" % client.transport._host, args[1]) - - -def test_list_user_workloads_config_maps_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_config_maps( - environments.ListUserWorkloadsConfigMapsRequest(), - parent='parent_value', - ) - - -def test_list_user_workloads_config_maps_rest_pager(transport: str = 'rest'): - client = EnvironmentsClient( - 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 = ( - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - next_page_token='abc', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[], - next_page_token='def', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - ], - next_page_token='ghi', - ), - environments.ListUserWorkloadsConfigMapsResponse( - user_workloads_config_maps=[ - environments.UserWorkloadsConfigMap(), - environments.UserWorkloadsConfigMap(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(environments.ListUserWorkloadsConfigMapsResponse.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/environments/sample3'} - - pager = client.list_user_workloads_config_maps(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, environments.UserWorkloadsConfigMap) - for i in results) - - pages = list(client.list_user_workloads_config_maps(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_update_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user_workloads_config_map(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_user_workloads_config_map_rest_flattened(): - client = EnvironmentsClient( - 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 = environments.UserWorkloadsConfigMap() - - # get arguments that satisfy an http rule for this method - sample_request = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - user_workloads_config_map=environments.UserWorkloadsConfigMap(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 = environments.UserWorkloadsConfigMap.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.update_user_workloads_config_map(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) - - -def test_update_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.UpdateUserWorkloadsConfigMapRequest(), - user_workloads_config_map=environments.UserWorkloadsConfigMap(name='name_value'), - ) - - -def test_delete_user_workloads_config_map_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 = EnvironmentsClient( - 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_user_workloads_config_map 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_user_workloads_config_map] = mock_rpc - - request = {} - client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user_workloads_config_map(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_user_workloads_config_map_rest_required_fields(request_type=environments.DeleteUserWorkloadsConfigMapRequest): - transport_class = transports.EnvironmentsRestTransport - - 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_user_workloads_config_map._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_user_workloads_config_map._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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # 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 = '' - - response_value._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_user_workloads_config_map(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_user_workloads_config_map_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_user_workloads_config_map._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_user_workloads_config_map_rest_flattened(): - client = EnvironmentsClient( - 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 = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = '' - response_value._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_user_workloads_config_map(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}" % client.transport._host, args[1]) - - -def test_delete_user_workloads_config_map_rest_flattened_error(transport: str = 'rest'): - client = EnvironmentsClient( - 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_user_workloads_config_map( - environments.DeleteUserWorkloadsConfigMapRequest(), - name='name_value', - ) - - -def test_save_snapshot_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 = EnvironmentsClient( - 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.save_snapshot 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.save_snapshot] = mock_rpc - - request = {} - client.save_snapshot(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.save_snapshot(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_load_snapshot_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 = EnvironmentsClient( - 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.load_snapshot 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.load_snapshot] = mock_rpc - - request = {} - client.load_snapshot(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.load_snapshot(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_database_failover_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 = EnvironmentsClient( - 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.database_failover 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.database_failover] = mock_rpc - - request = {} - client.database_failover(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.database_failover(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_fetch_database_properties_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 = EnvironmentsClient( - 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.fetch_database_properties 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.fetch_database_properties] = mock_rpc - - request = {} - client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_database_properties(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_fetch_database_properties_rest_required_fields(request_type=environments.FetchDatabasePropertiesRequest): - transport_class = transports.EnvironmentsRestTransport - - request_init = {} - request_init["environment"] = "" - 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()).fetch_database_properties._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["environment"] = 'environment_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_database_properties._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "environment" in jsonified_request - assert jsonified_request["environment"] == 'environment_value' - - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = environments.FetchDatabasePropertiesResponse() - # 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 = environments.FetchDatabasePropertiesResponse.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.fetch_database_properties(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_fetch_database_properties_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.fetch_database_properties._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("environment", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EnvironmentsClient( - 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 = EnvironmentsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EnvironmentsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EnvironmentsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - transports.EnvironmentsRestTransport, -]) -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 = EnvironmentsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = EnvironmentsClient( - 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_environment_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateEnvironmentRequest() - - 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_environment_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value = environments.Environment() - client.get_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetEnvironmentRequest() - - 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_environments_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - call.return_value = environments.ListEnvironmentsResponse() - client.list_environments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListEnvironmentsRequest() - - 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_environment_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateEnvironmentRequest() - - 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_environment_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteEnvironmentRequest() - - 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_restart_web_server_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.restart_web_server), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.restart_web_server(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.RestartWebServerRequest() - - 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_check_upgrade_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.check_upgrade(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CheckUpgradeRequest() - - 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_execute_airflow_command_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - call.return_value = environments.ExecuteAirflowCommandResponse() - client.execute_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ExecuteAirflowCommandRequest() - - 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_stop_airflow_command_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - call.return_value = environments.StopAirflowCommandResponse() - client.stop_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.StopAirflowCommandRequest() - - 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_poll_airflow_command_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - call.return_value = environments.PollAirflowCommandResponse() - client.poll_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.PollAirflowCommandRequest() - - 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_workloads_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - call.return_value = environments.ListWorkloadsResponse() - client.list_workloads(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListWorkloadsRequest() - - 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_user_workloads_secret_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.create_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.get_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsSecretRequest() - - 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_user_workloads_secrets_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - call.return_value = environments.ListUserWorkloadsSecretsResponse() - client.list_user_workloads_secrets(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsSecretsRequest() - - 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_user_workloads_secret_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - call.return_value = environments.UserWorkloadsSecret() - client.update_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - call.return_value = None - client.delete_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsSecretRequest() - - 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_user_workloads_config_map_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.create_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.get_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_maps_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - call.return_value = environments.ListUserWorkloadsConfigMapsResponse() - client.list_user_workloads_config_maps(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsConfigMapsRequest() - - 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_user_workloads_config_map_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - call.return_value = environments.UserWorkloadsConfigMap() - client.update_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - call.return_value = None - client.delete_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsConfigMapRequest() - - 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_save_snapshot_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.save_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.SaveSnapshotRequest() - - 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_load_snapshot_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.load_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.LoadSnapshotRequest() - - 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_database_failover_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.database_failover(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DatabaseFailoverRequest() - - 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_fetch_database_properties_empty_call_grpc(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - call.return_value = environments.FetchDatabasePropertiesResponse() - client.fetch_database_properties(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.FetchDatabasePropertiesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = EnvironmentsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = EnvironmentsAsyncClient( - 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_environment_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__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_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateEnvironmentRequest() - - 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_environment_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.Environment( - name='name_value', - uuid='uuid_value', - state=environments.Environment.State.CREATING, - satisfies_pzs=True, - satisfies_pzi=True, - )) - await client.get_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetEnvironmentRequest() - - 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_environments_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListEnvironmentsResponse( - next_page_token='next_page_token_value', - )) - await client.list_environments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListEnvironmentsRequest() - - 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_environment_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__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_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateEnvironmentRequest() - - 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_environment_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__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_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteEnvironmentRequest() - - 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_restart_web_server_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.restart_web_server), - '__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.restart_web_server(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.RestartWebServerRequest() - - 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_check_upgrade_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__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.check_upgrade(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CheckUpgradeRequest() - - 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_execute_airflow_command_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ExecuteAirflowCommandResponse( - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - error='error_value', - )) - await client.execute_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ExecuteAirflowCommandRequest() - - 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_stop_airflow_command_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.StopAirflowCommandResponse( - is_done=True, - output=['output_value'], - )) - await client.stop_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.StopAirflowCommandRequest() - - 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_poll_airflow_command_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.PollAirflowCommandResponse( - output_end=True, - )) - await client.poll_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.PollAirflowCommandRequest() - - 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_workloads_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListWorkloadsResponse( - next_page_token='next_page_token_value', - )) - await client.list_workloads(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListWorkloadsRequest() - - 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_user_workloads_secret_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - await client.create_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - await client.get_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsSecretRequest() - - 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_user_workloads_secrets_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsSecretsResponse( - next_page_token='next_page_token_value', - )) - await client.list_user_workloads_secrets(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsSecretsRequest() - - 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_user_workloads_secret_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsSecret( - name='name_value', - )) - await client.update_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsSecretRequest() - - 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_user_workloads_config_map_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - await client.create_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - await client.get_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_maps_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.ListUserWorkloadsConfigMapsResponse( - next_page_token='next_page_token_value', - )) - await client.list_user_workloads_config_maps(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsConfigMapsRequest() - - 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_user_workloads_config_map_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.UserWorkloadsConfigMap( - name='name_value', - )) - await client.update_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsConfigMapRequest() - - 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_save_snapshot_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__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.save_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.SaveSnapshotRequest() - - 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_load_snapshot_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__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.load_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.LoadSnapshotRequest() - - 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_database_failover_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__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.database_failover(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DatabaseFailoverRequest() - - 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_fetch_database_properties_empty_call_grpc_asyncio(): - client = EnvironmentsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(environments.FetchDatabasePropertiesResponse( - primary_gce_zone='primary_gce_zone_value', - secondary_gce_zone='secondary_gce_zone_value', - is_failover_replica_available=True, - )) - await client.fetch_database_properties(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.FetchDatabasePropertiesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = EnvironmentsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_environment_rest_bad_request(request_type=environments.CreateEnvironmentRequest): - client = EnvironmentsClient( - 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_environment(request) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateEnvironmentRequest, - dict, -]) -def test_create_environment_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["environment"] = {'name': 'name_value', 'config': {'gke_cluster': 'gke_cluster_value', 'dag_gcs_prefix': 'dag_gcs_prefix_value', 'node_count': 1070, 'software_config': {'image_version': 'image_version_value', 'airflow_config_overrides': {}, 'pypi_packages': {}, 'env_variables': {}, 'python_version': 'python_version_value', 'scheduler_count': 1607, 'cloud_data_lineage_integration': {'enabled': True}, 'web_server_plugins_mode': 1}, 'node_config': {'location': 'location_value', 'machine_type': 'machine_type_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'disk_size_gb': 1261, 'oauth_scopes': ['oauth_scopes_value1', 'oauth_scopes_value2'], 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'ip_allocation_policy': {'use_ip_aliases': True, 'cluster_secondary_range_name': 'cluster_secondary_range_name_value', 'services_secondary_range_name': 'services_secondary_range_name_value', 'cluster_ipv4_cidr_block': 'cluster_ipv4_cidr_block_value', 'services_ipv4_cidr_block': 'services_ipv4_cidr_block_value'}, 'max_pods_per_node': 1798, 'enable_ip_masq_agent': True, 'composer_network_attachment': 'composer_network_attachment_value', 'composer_internal_ipv4_cidr_block': 'composer_internal_ipv4_cidr_block_value'}, 'private_environment_config': {'enable_private_environment': True, 'enable_private_builds_only': True, 'private_cluster_config': {'enable_private_endpoint': True, 'master_ipv4_cidr_block': 'master_ipv4_cidr_block_value', 'master_ipv4_reserved_range': 'master_ipv4_reserved_range_value'}, 'web_server_ipv4_cidr_block': 'web_server_ipv4_cidr_block_value', 'cloud_sql_ipv4_cidr_block': 'cloud_sql_ipv4_cidr_block_value', 'web_server_ipv4_reserved_range': 'web_server_ipv4_reserved_range_value', 'cloud_composer_network_ipv4_cidr_block': 'cloud_composer_network_ipv4_cidr_block_value', 'cloud_composer_network_ipv4_reserved_range': 'cloud_composer_network_ipv4_reserved_range_value', 'enable_privately_used_public_ips': True, 'cloud_composer_connection_subnetwork': 'cloud_composer_connection_subnetwork_value', 'networking_config': {'connection_type': 1}}, 'web_server_network_access_control': {'allowed_ip_ranges': [{'value': 'value_value', 'description': 'description_value'}]}, 'database_config': {'machine_type': 'machine_type_value', 'zone': 'zone_value'}, 'web_server_config': {'machine_type': 'machine_type_value'}, 'airflow_uri': 'airflow_uri_value', 'airflow_byoid_uri': 'airflow_byoid_uri_value', 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'maintenance_window': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'recurrence': 'recurrence_value'}, 'workloads_config': {'scheduler': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}, 'web_server': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053}, 'worker': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'min_count': 972, 'max_count': 974}, 'triggerer': {'count': 553, 'cpu': 0.328, 'memory_gb': 0.961}, 'dag_processor': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}}, 'environment_size': 1, 'master_authorized_networks_config': {'enabled': True, 'cidr_blocks': [{'display_name': 'display_name_value', 'cidr_block': 'cidr_block_value'}]}, 'recovery_config': {'scheduled_snapshots_config': {'enabled': True, 'snapshot_location': 'snapshot_location_value', 'snapshot_creation_schedule': 'snapshot_creation_schedule_value', 'time_zone': 'time_zone_value'}}, 'data_retention_config': {'airflow_database_retention_days': 3279, 'task_logs_retention_config': {'storage_mode': 1}, 'airflow_metadata_retention_config': {'retention_mode': 1, 'retention_days': 1512}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': True, 'satisfies_pzi': True, 'storage_config': {'bucket': 'bucket_value'}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = environments.CreateEnvironmentRequest.meta.fields["environment"] - - 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["environment"].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["environment"][field])): - del request_init["environment"][field][i][subfield] - else: - del request_init["environment"][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_environment(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_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_environment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.CreateEnvironmentRequest.pb(environments.CreateEnvironmentRequest()) - 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 = environments.CreateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.create_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_environment_rest_bad_request(request_type=environments.GetEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) - - -@pytest.mark.parametrize("request_type", [ - environments.GetEnvironmentRequest, - dict, -]) -def test_get_environment_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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 = environments.Environment( - name='name_value', - uuid='uuid_value', - state=environments.Environment.State.CREATING, - satisfies_pzs=True, - satisfies_pzi=True, - ) - - # 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 = environments.Environment.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_environment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.Environment) - assert response.name == 'name_value' - assert response.uuid == 'uuid_value' - assert response.state == environments.Environment.State.CREATING - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_environment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.GetEnvironmentRequest.pb(environments.GetEnvironmentRequest()) - 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 = environments.Environment.to_json(environments.Environment()) - req.return_value.content = return_value - - request = environments.GetEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.Environment() - post_with_metadata.return_value = environments.Environment(), metadata - - client.get_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_environments_rest_bad_request(request_type=environments.ListEnvironmentsRequest): - client = EnvironmentsClient( - 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_environments(request) - - -@pytest.mark.parametrize("request_type", [ - environments.ListEnvironmentsRequest, - dict, -]) -def test_list_environments_rest_call_success(request_type): - client = EnvironmentsClient( - 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 = environments.ListEnvironmentsResponse( - 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 = environments.ListEnvironmentsResponse.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_environments(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_environments_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_environments") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_environments_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_environments") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.ListEnvironmentsRequest.pb(environments.ListEnvironmentsRequest()) - 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 = environments.ListEnvironmentsResponse.to_json(environments.ListEnvironmentsResponse()) - req.return_value.content = return_value - - request = environments.ListEnvironmentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListEnvironmentsResponse() - post_with_metadata.return_value = environments.ListEnvironmentsResponse(), metadata - - client.list_environments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_environment_rest_bad_request(request_type=environments.UpdateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateEnvironmentRequest, - dict, -]) -def test_update_environment_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3'} - request_init["environment"] = {'name': 'name_value', 'config': {'gke_cluster': 'gke_cluster_value', 'dag_gcs_prefix': 'dag_gcs_prefix_value', 'node_count': 1070, 'software_config': {'image_version': 'image_version_value', 'airflow_config_overrides': {}, 'pypi_packages': {}, 'env_variables': {}, 'python_version': 'python_version_value', 'scheduler_count': 1607, 'cloud_data_lineage_integration': {'enabled': True}, 'web_server_plugins_mode': 1}, 'node_config': {'location': 'location_value', 'machine_type': 'machine_type_value', 'network': 'network_value', 'subnetwork': 'subnetwork_value', 'disk_size_gb': 1261, 'oauth_scopes': ['oauth_scopes_value1', 'oauth_scopes_value2'], 'service_account': 'service_account_value', 'tags': ['tags_value1', 'tags_value2'], 'ip_allocation_policy': {'use_ip_aliases': True, 'cluster_secondary_range_name': 'cluster_secondary_range_name_value', 'services_secondary_range_name': 'services_secondary_range_name_value', 'cluster_ipv4_cidr_block': 'cluster_ipv4_cidr_block_value', 'services_ipv4_cidr_block': 'services_ipv4_cidr_block_value'}, 'max_pods_per_node': 1798, 'enable_ip_masq_agent': True, 'composer_network_attachment': 'composer_network_attachment_value', 'composer_internal_ipv4_cidr_block': 'composer_internal_ipv4_cidr_block_value'}, 'private_environment_config': {'enable_private_environment': True, 'enable_private_builds_only': True, 'private_cluster_config': {'enable_private_endpoint': True, 'master_ipv4_cidr_block': 'master_ipv4_cidr_block_value', 'master_ipv4_reserved_range': 'master_ipv4_reserved_range_value'}, 'web_server_ipv4_cidr_block': 'web_server_ipv4_cidr_block_value', 'cloud_sql_ipv4_cidr_block': 'cloud_sql_ipv4_cidr_block_value', 'web_server_ipv4_reserved_range': 'web_server_ipv4_reserved_range_value', 'cloud_composer_network_ipv4_cidr_block': 'cloud_composer_network_ipv4_cidr_block_value', 'cloud_composer_network_ipv4_reserved_range': 'cloud_composer_network_ipv4_reserved_range_value', 'enable_privately_used_public_ips': True, 'cloud_composer_connection_subnetwork': 'cloud_composer_connection_subnetwork_value', 'networking_config': {'connection_type': 1}}, 'web_server_network_access_control': {'allowed_ip_ranges': [{'value': 'value_value', 'description': 'description_value'}]}, 'database_config': {'machine_type': 'machine_type_value', 'zone': 'zone_value'}, 'web_server_config': {'machine_type': 'machine_type_value'}, 'airflow_uri': 'airflow_uri_value', 'airflow_byoid_uri': 'airflow_byoid_uri_value', 'encryption_config': {'kms_key_name': 'kms_key_name_value'}, 'maintenance_window': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}, 'recurrence': 'recurrence_value'}, 'workloads_config': {'scheduler': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}, 'web_server': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053}, 'worker': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'min_count': 972, 'max_count': 974}, 'triggerer': {'count': 553, 'cpu': 0.328, 'memory_gb': 0.961}, 'dag_processor': {'cpu': 0.328, 'memory_gb': 0.961, 'storage_gb': 0.1053, 'count': 553}}, 'environment_size': 1, 'master_authorized_networks_config': {'enabled': True, 'cidr_blocks': [{'display_name': 'display_name_value', 'cidr_block': 'cidr_block_value'}]}, 'recovery_config': {'scheduled_snapshots_config': {'enabled': True, 'snapshot_location': 'snapshot_location_value', 'snapshot_creation_schedule': 'snapshot_creation_schedule_value', 'time_zone': 'time_zone_value'}}, 'data_retention_config': {'airflow_database_retention_days': 3279, 'task_logs_retention_config': {'storage_mode': 1}, 'airflow_metadata_retention_config': {'retention_mode': 1, 'retention_days': 1512}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': True, 'satisfies_pzi': True, 'storage_config': {'bucket': 'bucket_value'}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = environments.UpdateEnvironmentRequest.meta.fields["environment"] - - 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["environment"].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["environment"][field])): - del request_init["environment"][field][i][subfield] - else: - del request_init["environment"][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_environment(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_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_environment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.UpdateEnvironmentRequest.pb(environments.UpdateEnvironmentRequest()) - 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 = environments.UpdateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.update_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_environment_rest_bad_request(request_type=environments.DeleteEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(request) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteEnvironmentRequest, - dict, -]) -def test_delete_environment_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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_environment(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_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_delete_environment") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_delete_environment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_delete_environment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.DeleteEnvironmentRequest.pb(environments.DeleteEnvironmentRequest()) - 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 = environments.DeleteEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.delete_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_restart_web_server_rest_bad_request(request_type=environments.RestartWebServerRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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.restart_web_server(request) - - -@pytest.mark.parametrize("request_type", [ - environments.RestartWebServerRequest, - dict, -]) -def test_restart_web_server_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/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.restart_web_server(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_restart_web_server_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_restart_web_server") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_restart_web_server_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_restart_web_server") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.RestartWebServerRequest.pb(environments.RestartWebServerRequest()) - 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 = environments.RestartWebServerRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.restart_web_server(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_check_upgrade_rest_bad_request(request_type=environments.CheckUpgradeRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.check_upgrade(request) - - -@pytest.mark.parametrize("request_type", [ - environments.CheckUpgradeRequest, - dict, -]) -def test_check_upgrade_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.check_upgrade(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_check_upgrade_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_check_upgrade") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_check_upgrade_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_check_upgrade") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.CheckUpgradeRequest.pb(environments.CheckUpgradeRequest()) - 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 = environments.CheckUpgradeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.check_upgrade(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_execute_airflow_command_rest_bad_request(request_type=environments.ExecuteAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.execute_airflow_command(request) - - -@pytest.mark.parametrize("request_type", [ - environments.ExecuteAirflowCommandRequest, - dict, -]) -def test_execute_airflow_command_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.ExecuteAirflowCommandResponse( - execution_id='execution_id_value', - pod='pod_value', - pod_namespace='pod_namespace_value', - error='error_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 = environments.ExecuteAirflowCommandResponse.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.execute_airflow_command(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.ExecuteAirflowCommandResponse) - assert response.execution_id == 'execution_id_value' - assert response.pod == 'pod_value' - assert response.pod_namespace == 'pod_namespace_value' - assert response.error == 'error_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_execute_airflow_command_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_execute_airflow_command") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_execute_airflow_command_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_execute_airflow_command") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.ExecuteAirflowCommandRequest.pb(environments.ExecuteAirflowCommandRequest()) - 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 = environments.ExecuteAirflowCommandResponse.to_json(environments.ExecuteAirflowCommandResponse()) - req.return_value.content = return_value - - request = environments.ExecuteAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ExecuteAirflowCommandResponse() - post_with_metadata.return_value = environments.ExecuteAirflowCommandResponse(), metadata - - client.execute_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_stop_airflow_command_rest_bad_request(request_type=environments.StopAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.stop_airflow_command(request) - - -@pytest.mark.parametrize("request_type", [ - environments.StopAirflowCommandRequest, - dict, -]) -def test_stop_airflow_command_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.StopAirflowCommandResponse( - is_done=True, - output=['output_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 = environments.StopAirflowCommandResponse.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.stop_airflow_command(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.StopAirflowCommandResponse) - assert response.is_done is True - assert response.output == ['output_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_stop_airflow_command_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_stop_airflow_command") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_stop_airflow_command_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_stop_airflow_command") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.StopAirflowCommandRequest.pb(environments.StopAirflowCommandRequest()) - 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 = environments.StopAirflowCommandResponse.to_json(environments.StopAirflowCommandResponse()) - req.return_value.content = return_value - - request = environments.StopAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.StopAirflowCommandResponse() - post_with_metadata.return_value = environments.StopAirflowCommandResponse(), metadata - - client.stop_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_poll_airflow_command_rest_bad_request(request_type=environments.PollAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.poll_airflow_command(request) - - -@pytest.mark.parametrize("request_type", [ - environments.PollAirflowCommandRequest, - dict, -]) -def test_poll_airflow_command_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.PollAirflowCommandResponse( - output_end=True, - ) - - # 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 = environments.PollAirflowCommandResponse.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.poll_airflow_command(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.PollAirflowCommandResponse) - assert response.output_end is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_poll_airflow_command_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_poll_airflow_command") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_poll_airflow_command_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_poll_airflow_command") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.PollAirflowCommandRequest.pb(environments.PollAirflowCommandRequest()) - 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 = environments.PollAirflowCommandResponse.to_json(environments.PollAirflowCommandResponse()) - req.return_value.content = return_value - - request = environments.PollAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.PollAirflowCommandResponse() - post_with_metadata.return_value = environments.PollAirflowCommandResponse(), metadata - - client.poll_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_workloads_rest_bad_request(request_type=environments.ListWorkloadsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_workloads(request) - - -@pytest.mark.parametrize("request_type", [ - environments.ListWorkloadsRequest, - dict, -]) -def test_list_workloads_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListWorkloadsResponse( - 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 = environments.ListWorkloadsResponse.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_workloads(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWorkloadsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_workloads_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_workloads") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_workloads_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_workloads") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.ListWorkloadsRequest.pb(environments.ListWorkloadsRequest()) - 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 = environments.ListWorkloadsResponse.to_json(environments.ListWorkloadsResponse()) - req.return_value.content = return_value - - request = environments.ListWorkloadsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListWorkloadsResponse() - post_with_metadata.return_value = environments.ListWorkloadsResponse(), metadata - - client.list_workloads(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_user_workloads_secret_rest_bad_request(request_type=environments.CreateUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_secret(request) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsSecretRequest, - dict, -]) -def test_create_user_workloads_secret_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} - request_init["user_workloads_secret"] = {'name': 'name_value', 'data': {}} - # 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 = environments.CreateUserWorkloadsSecretRequest.meta.fields["user_workloads_secret"] - - 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["user_workloads_secret"].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["user_workloads_secret"][field])): - del request_init["user_workloads_secret"][field][i][subfield] - else: - del request_init["user_workloads_secret"][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 = environments.UserWorkloadsSecret( - 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 = environments.UserWorkloadsSecret.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.create_user_workloads_secret(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_user_workloads_secret_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_user_workloads_secret") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_user_workloads_secret_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_user_workloads_secret") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.CreateUserWorkloadsSecretRequest.pb(environments.CreateUserWorkloadsSecretRequest()) - 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - req.return_value.content = return_value - - request = environments.CreateUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata - - client.create_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_user_workloads_secret_rest_bad_request(request_type=environments.GetUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsSecretRequest, - dict, -]) -def test_get_user_workloads_secret_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = environments.UserWorkloadsSecret( - 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 = environments.UserWorkloadsSecret.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_user_workloads_secret(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_user_workloads_secret_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_user_workloads_secret") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_user_workloads_secret_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_user_workloads_secret") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.GetUserWorkloadsSecretRequest.pb(environments.GetUserWorkloadsSecretRequest()) - 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - req.return_value.content = return_value - - request = environments.GetUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata - - client.get_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_user_workloads_secrets_rest_bad_request(request_type=environments.ListUserWorkloadsSecretsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_secrets(request) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsSecretsRequest, - dict, -]) -def test_list_user_workloads_secrets_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsSecretsResponse( - 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 = environments.ListUserWorkloadsSecretsResponse.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_user_workloads_secrets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsSecretsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_user_workloads_secrets_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_user_workloads_secrets") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_user_workloads_secrets_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_user_workloads_secrets") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.ListUserWorkloadsSecretsRequest.pb(environments.ListUserWorkloadsSecretsRequest()) - 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 = environments.ListUserWorkloadsSecretsResponse.to_json(environments.ListUserWorkloadsSecretsResponse()) - req.return_value.content = return_value - - request = environments.ListUserWorkloadsSecretsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListUserWorkloadsSecretsResponse() - post_with_metadata.return_value = environments.ListUserWorkloadsSecretsResponse(), metadata - - client.list_user_workloads_secrets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_user_workloads_secret_rest_bad_request(request_type=environments.UpdateUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateUserWorkloadsSecretRequest, - dict, -]) -def test_update_user_workloads_secret_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'user_workloads_secret': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4'}} - request_init["user_workloads_secret"] = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/sample4', 'data': {}} - # 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 = environments.UpdateUserWorkloadsSecretRequest.meta.fields["user_workloads_secret"] - - 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["user_workloads_secret"].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["user_workloads_secret"][field])): - del request_init["user_workloads_secret"][field][i][subfield] - else: - del request_init["user_workloads_secret"][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 = environments.UserWorkloadsSecret( - 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 = environments.UserWorkloadsSecret.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.update_user_workloads_secret(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsSecret) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_user_workloads_secret_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_user_workloads_secret") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_user_workloads_secret_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_user_workloads_secret") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.UpdateUserWorkloadsSecretRequest.pb(environments.UpdateUserWorkloadsSecretRequest()) - 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 = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - req.return_value.content = return_value - - request = environments.UpdateUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - post_with_metadata.return_value = environments.UserWorkloadsSecret(), metadata - - client.update_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_user_workloads_secret_rest_bad_request(request_type=environments.DeleteUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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_user_workloads_secret(request) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsSecretRequest, - dict, -]) -def test_delete_user_workloads_secret_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsSecrets/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 = 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_user_workloads_secret(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_user_workloads_secret_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "pre_delete_user_workloads_secret") as pre: - pre.assert_not_called() - pb_message = environments.DeleteUserWorkloadsSecretRequest.pb(environments.DeleteUserWorkloadsSecretRequest()) - 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"} - - request = environments.DeleteUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_create_user_workloads_config_map_rest_bad_request(request_type=environments.CreateUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_config_map(request) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsConfigMapRequest, - dict, -]) -def test_create_user_workloads_config_map_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/sample3'} - request_init["user_workloads_config_map"] = {'name': 'name_value', 'data': {}} - # 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 = environments.CreateUserWorkloadsConfigMapRequest.meta.fields["user_workloads_config_map"] - - 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["user_workloads_config_map"].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["user_workloads_config_map"][field])): - del request_init["user_workloads_config_map"][field][i][subfield] - else: - del request_init["user_workloads_config_map"][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 = environments.UserWorkloadsConfigMap( - 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 = environments.UserWorkloadsConfigMap.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.create_user_workloads_config_map(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_user_workloads_config_map_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_create_user_workloads_config_map") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_create_user_workloads_config_map_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_create_user_workloads_config_map") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.CreateUserWorkloadsConfigMapRequest.pb(environments.CreateUserWorkloadsConfigMapRequest()) - 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - req.return_value.content = return_value - - request = environments.CreateUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata - - client.create_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_user_workloads_config_map_rest_bad_request(request_type=environments.GetUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsConfigMapRequest, - dict, -]) -def test_get_user_workloads_config_map_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = environments.UserWorkloadsConfigMap( - 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 = environments.UserWorkloadsConfigMap.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_user_workloads_config_map(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_user_workloads_config_map_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_get_user_workloads_config_map") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_get_user_workloads_config_map_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_get_user_workloads_config_map") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.GetUserWorkloadsConfigMapRequest.pb(environments.GetUserWorkloadsConfigMapRequest()) - 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - req.return_value.content = return_value - - request = environments.GetUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata - - client.get_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_user_workloads_config_maps_rest_bad_request(request_type=environments.ListUserWorkloadsConfigMapsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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_user_workloads_config_maps(request) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsConfigMapsRequest, - dict, -]) -def test_list_user_workloads_config_maps_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/environments/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 = environments.ListUserWorkloadsConfigMapsResponse( - 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 = environments.ListUserWorkloadsConfigMapsResponse.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_user_workloads_config_maps(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUserWorkloadsConfigMapsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_user_workloads_config_maps_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_list_user_workloads_config_maps") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_list_user_workloads_config_maps_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_list_user_workloads_config_maps") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.ListUserWorkloadsConfigMapsRequest.pb(environments.ListUserWorkloadsConfigMapsRequest()) - 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 = environments.ListUserWorkloadsConfigMapsResponse.to_json(environments.ListUserWorkloadsConfigMapsResponse()) - req.return_value.content = return_value - - request = environments.ListUserWorkloadsConfigMapsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListUserWorkloadsConfigMapsResponse() - post_with_metadata.return_value = environments.ListUserWorkloadsConfigMapsResponse(), metadata - - client.list_user_workloads_config_maps(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_user_workloads_config_map_rest_bad_request(request_type=environments.UpdateUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateUserWorkloadsConfigMapRequest, - dict, -]) -def test_update_user_workloads_config_map_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'user_workloads_config_map': {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4'}} - request_init["user_workloads_config_map"] = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/sample4', 'data': {}} - # 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 = environments.UpdateUserWorkloadsConfigMapRequest.meta.fields["user_workloads_config_map"] - - 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["user_workloads_config_map"].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["user_workloads_config_map"][field])): - del request_init["user_workloads_config_map"][field][i][subfield] - else: - del request_init["user_workloads_config_map"][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 = environments.UserWorkloadsConfigMap( - 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 = environments.UserWorkloadsConfigMap.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.update_user_workloads_config_map(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.UserWorkloadsConfigMap) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_user_workloads_config_map_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_update_user_workloads_config_map") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_update_user_workloads_config_map_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_update_user_workloads_config_map") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.UpdateUserWorkloadsConfigMapRequest.pb(environments.UpdateUserWorkloadsConfigMapRequest()) - 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 = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - req.return_value.content = return_value - - request = environments.UpdateUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - post_with_metadata.return_value = environments.UserWorkloadsConfigMap(), metadata - - client.update_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_user_workloads_config_map_rest_bad_request(request_type=environments.DeleteUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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_user_workloads_config_map(request) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsConfigMapRequest, - dict, -]) -def test_delete_user_workloads_config_map_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/environments/sample3/userWorkloadsConfigMaps/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 = 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_user_workloads_config_map(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_user_workloads_config_map_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "pre_delete_user_workloads_config_map") as pre: - pre.assert_not_called() - pb_message = environments.DeleteUserWorkloadsConfigMapRequest.pb(environments.DeleteUserWorkloadsConfigMapRequest()) - 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"} - - request = environments.DeleteUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_save_snapshot_rest_bad_request(request_type=environments.SaveSnapshotRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.save_snapshot(request) - - -@pytest.mark.parametrize("request_type", [ - environments.SaveSnapshotRequest, - dict, -]) -def test_save_snapshot_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.save_snapshot(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_save_snapshot_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_save_snapshot") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_save_snapshot_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_save_snapshot") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.SaveSnapshotRequest.pb(environments.SaveSnapshotRequest()) - 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 = environments.SaveSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.save_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_load_snapshot_rest_bad_request(request_type=environments.LoadSnapshotRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.load_snapshot(request) - - -@pytest.mark.parametrize("request_type", [ - environments.LoadSnapshotRequest, - dict, -]) -def test_load_snapshot_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.load_snapshot(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_load_snapshot_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_load_snapshot") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_load_snapshot_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_load_snapshot") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.LoadSnapshotRequest.pb(environments.LoadSnapshotRequest()) - 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 = environments.LoadSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.load_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_database_failover_rest_bad_request(request_type=environments.DatabaseFailoverRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.database_failover(request) - - -@pytest.mark.parametrize("request_type", [ - environments.DatabaseFailoverRequest, - dict, -]) -def test_database_failover_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.database_failover(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_database_failover_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_database_failover") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_database_failover_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_database_failover") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.DatabaseFailoverRequest.pb(environments.DatabaseFailoverRequest()) - 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 = environments.DatabaseFailoverRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.database_failover(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_fetch_database_properties_rest_bad_request(request_type=environments.FetchDatabasePropertiesRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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.fetch_database_properties(request) - - -@pytest.mark.parametrize("request_type", [ - environments.FetchDatabasePropertiesRequest, - dict, -]) -def test_fetch_database_properties_rest_call_success(request_type): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'environment': 'projects/sample1/locations/sample2/environments/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 = environments.FetchDatabasePropertiesResponse( - primary_gce_zone='primary_gce_zone_value', - secondary_gce_zone='secondary_gce_zone_value', - is_failover_replica_available=True, - ) - - # 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 = environments.FetchDatabasePropertiesResponse.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.fetch_database_properties(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, environments.FetchDatabasePropertiesResponse) - assert response.primary_gce_zone == 'primary_gce_zone_value' - assert response.secondary_gce_zone == 'secondary_gce_zone_value' - assert response.is_failover_replica_available is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_database_properties_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EnvironmentsRestInterceptor(), - ) - client = EnvironmentsClient(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.EnvironmentsRestInterceptor, "post_fetch_database_properties") as post, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "post_fetch_database_properties_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EnvironmentsRestInterceptor, "pre_fetch_database_properties") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = environments.FetchDatabasePropertiesRequest.pb(environments.FetchDatabasePropertiesRequest()) - 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 = environments.FetchDatabasePropertiesResponse.to_json(environments.FetchDatabasePropertiesResponse()) - req.return_value.content = return_value - - request = environments.FetchDatabasePropertiesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.FetchDatabasePropertiesResponse() - post_with_metadata.return_value = environments.FetchDatabasePropertiesResponse(), metadata - - client.fetch_database_properties(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = EnvironmentsClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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_environment_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - client.create_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateEnvironmentRequest() - - 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_environment_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - client.get_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetEnvironmentRequest() - - 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_environments_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - client.list_environments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListEnvironmentsRequest() - - 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_environment_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - client.update_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateEnvironmentRequest() - - 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_environment_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - client.delete_environment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteEnvironmentRequest() - - 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_restart_web_server_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.restart_web_server), - '__call__') as call: - client.restart_web_server(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.RestartWebServerRequest() - - 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_check_upgrade_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - client.check_upgrade(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CheckUpgradeRequest() - - 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_execute_airflow_command_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.execute_airflow_command), - '__call__') as call: - client.execute_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ExecuteAirflowCommandRequest() - - 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_stop_airflow_command_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.stop_airflow_command), - '__call__') as call: - client.stop_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.StopAirflowCommandRequest() - - 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_poll_airflow_command_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.poll_airflow_command), - '__call__') as call: - client.poll_airflow_command(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.PollAirflowCommandRequest() - - 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_workloads_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - client.list_workloads(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListWorkloadsRequest() - - 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_user_workloads_secret_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_secret), - '__call__') as call: - client.create_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_secret), - '__call__') as call: - client.get_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsSecretRequest() - - 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_user_workloads_secrets_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_secrets), - '__call__') as call: - client.list_user_workloads_secrets(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsSecretsRequest() - - 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_user_workloads_secret_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_secret), - '__call__') as call: - client.update_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsSecretRequest() - - 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_user_workloads_secret_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_secret), - '__call__') as call: - client.delete_user_workloads_secret(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsSecretRequest() - - 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_user_workloads_config_map_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user_workloads_config_map), - '__call__') as call: - client.create_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.CreateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user_workloads_config_map), - '__call__') as call: - client.get_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.GetUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_maps_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_user_workloads_config_maps), - '__call__') as call: - client.list_user_workloads_config_maps(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.ListUserWorkloadsConfigMapsRequest() - - 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_user_workloads_config_map_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user_workloads_config_map), - '__call__') as call: - client.update_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.UpdateUserWorkloadsConfigMapRequest() - - 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_user_workloads_config_map_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user_workloads_config_map), - '__call__') as call: - client.delete_user_workloads_config_map(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DeleteUserWorkloadsConfigMapRequest() - - 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_save_snapshot_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - client.save_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.SaveSnapshotRequest() - - 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_load_snapshot_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - client.load_snapshot(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.LoadSnapshotRequest() - - 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_database_failover_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - client.database_failover(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.DatabaseFailoverRequest() - - 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_fetch_database_properties_empty_call_rest(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_database_properties), - '__call__') as call: - client.fetch_database_properties(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = environments.FetchDatabasePropertiesRequest() - - assert args[0] == request_msg - - -def test_environments_rest_lro_client(): - client = EnvironmentsClient( - 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 = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.EnvironmentsGrpcTransport, - ) - -def test_environments_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EnvironmentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_environments_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.orchestration.airflow.service_v1beta1.services.environments.transports.EnvironmentsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EnvironmentsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_environment', - 'get_environment', - 'list_environments', - 'update_environment', - 'delete_environment', - 'restart_web_server', - 'check_upgrade', - 'execute_airflow_command', - 'stop_airflow_command', - 'poll_airflow_command', - 'list_workloads', - 'create_user_workloads_secret', - 'get_user_workloads_secret', - 'list_user_workloads_secrets', - 'update_user_workloads_secret', - 'delete_user_workloads_secret', - 'create_user_workloads_config_map', - 'get_user_workloads_config_map', - 'list_user_workloads_config_maps', - 'update_user_workloads_config_map', - 'delete_user_workloads_config_map', - 'save_snapshot', - 'load_snapshot', - 'database_failover', - 'fetch_database_properties', - 'get_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_environments_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.orchestration.airflow.service_v1beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - 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_environments_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.orchestration.airflow.service_v1beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport() - adc.assert_called_once() - - -def test_environments_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) - EnvironmentsClient() - 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.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -def test_environments_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.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - transports.EnvironmentsRestTransport, - ], -) -def test_environments_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.EnvironmentsGrpcTransport, grpc_helpers), - (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_environments_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( - "composer.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="composer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_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_environments_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.EnvironmentsRestTransport ( - 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_environments_host_no_port(transport_name): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://composer.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_environments_host_with_port(transport_name): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'composer.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://composer.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_environments_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EnvironmentsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EnvironmentsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_environment._session - session2 = client2.transport.create_environment._session - assert session1 != session2 - session1 = client1.transport.get_environment._session - session2 = client2.transport.get_environment._session - assert session1 != session2 - session1 = client1.transport.list_environments._session - session2 = client2.transport.list_environments._session - assert session1 != session2 - session1 = client1.transport.update_environment._session - session2 = client2.transport.update_environment._session - assert session1 != session2 - session1 = client1.transport.delete_environment._session - session2 = client2.transport.delete_environment._session - assert session1 != session2 - session1 = client1.transport.restart_web_server._session - session2 = client2.transport.restart_web_server._session - assert session1 != session2 - session1 = client1.transport.check_upgrade._session - session2 = client2.transport.check_upgrade._session - assert session1 != session2 - session1 = client1.transport.execute_airflow_command._session - session2 = client2.transport.execute_airflow_command._session - assert session1 != session2 - session1 = client1.transport.stop_airflow_command._session - session2 = client2.transport.stop_airflow_command._session - assert session1 != session2 - session1 = client1.transport.poll_airflow_command._session - session2 = client2.transport.poll_airflow_command._session - assert session1 != session2 - session1 = client1.transport.list_workloads._session - session2 = client2.transport.list_workloads._session - assert session1 != session2 - session1 = client1.transport.create_user_workloads_secret._session - session2 = client2.transport.create_user_workloads_secret._session - assert session1 != session2 - session1 = client1.transport.get_user_workloads_secret._session - session2 = client2.transport.get_user_workloads_secret._session - assert session1 != session2 - session1 = client1.transport.list_user_workloads_secrets._session - session2 = client2.transport.list_user_workloads_secrets._session - assert session1 != session2 - session1 = client1.transport.update_user_workloads_secret._session - session2 = client2.transport.update_user_workloads_secret._session - assert session1 != session2 - session1 = client1.transport.delete_user_workloads_secret._session - session2 = client2.transport.delete_user_workloads_secret._session - assert session1 != session2 - session1 = client1.transport.create_user_workloads_config_map._session - session2 = client2.transport.create_user_workloads_config_map._session - assert session1 != session2 - session1 = client1.transport.get_user_workloads_config_map._session - session2 = client2.transport.get_user_workloads_config_map._session - assert session1 != session2 - session1 = client1.transport.list_user_workloads_config_maps._session - session2 = client2.transport.list_user_workloads_config_maps._session - assert session1 != session2 - session1 = client1.transport.update_user_workloads_config_map._session - session2 = client2.transport.update_user_workloads_config_map._session - assert session1 != session2 - session1 = client1.transport.delete_user_workloads_config_map._session - session2 = client2.transport.delete_user_workloads_config_map._session - assert session1 != session2 - session1 = client1.transport.save_snapshot._session - session2 = client2.transport.save_snapshot._session - assert session1 != session2 - session1 = client1.transport.load_snapshot._session - session2 = client2.transport.load_snapshot._session - assert session1 != session2 - session1 = client1.transport.database_failover._session - session2 = client2.transport.database_failover._session - assert session1 != session2 - session1 = client1.transport.fetch_database_properties._session - session2 = client2.transport.fetch_database_properties._session - assert session1 != session2 -def test_environments_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EnvironmentsGrpcTransport( - 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_environments_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EnvironmentsGrpcAsyncIOTransport( - 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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_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.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport]) -def test_environments_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_environments_grpc_lro_client(): - client = EnvironmentsClient( - 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_environments_grpc_lro_async_client(): - client = EnvironmentsAsyncClient( - 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_environment_path(): - project = "squid" - location = "clam" - environment = "whelk" - expected = "projects/{project}/locations/{location}/environments/{environment}".format(project=project, location=location, environment=environment, ) - actual = EnvironmentsClient.environment_path(project, location, environment) - assert expected == actual - - -def test_parse_environment_path(): - expected = { - "project": "octopus", - "location": "oyster", - "environment": "nudibranch", - } - path = EnvironmentsClient.environment_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_environment_path(path) - assert expected == actual - -def test_user_workloads_config_map_path(): - project = "cuttlefish" - location = "mussel" - environment = "winkle" - user_workloads_config_map = "nautilus" - expected = "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsConfigMaps/{user_workloads_config_map}".format(project=project, location=location, environment=environment, user_workloads_config_map=user_workloads_config_map, ) - actual = EnvironmentsClient.user_workloads_config_map_path(project, location, environment, user_workloads_config_map) - assert expected == actual - - -def test_parse_user_workloads_config_map_path(): - expected = { - "project": "scallop", - "location": "abalone", - "environment": "squid", - "user_workloads_config_map": "clam", - } - path = EnvironmentsClient.user_workloads_config_map_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_user_workloads_config_map_path(path) - assert expected == actual - -def test_user_workloads_secret_path(): - project = "whelk" - location = "octopus" - environment = "oyster" - user_workloads_secret = "nudibranch" - expected = "projects/{project}/locations/{location}/environments/{environment}/userWorkloadsSecrets/{user_workloads_secret}".format(project=project, location=location, environment=environment, user_workloads_secret=user_workloads_secret, ) - actual = EnvironmentsClient.user_workloads_secret_path(project, location, environment, user_workloads_secret) - assert expected == actual - - -def test_parse_user_workloads_secret_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "environment": "winkle", - "user_workloads_secret": "nautilus", - } - path = EnvironmentsClient.user_workloads_secret_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_user_workloads_secret_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EnvironmentsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = EnvironmentsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = EnvironmentsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = EnvironmentsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = EnvironmentsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.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 = EnvironmentsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = EnvironmentsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EnvironmentsClient.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.EnvironmentsTransport, '_prep_wrapped_messages') as prep: - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EnvironmentsTransport, '_prep_wrapped_messages') as prep: - transport_class = EnvironmentsClient.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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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_get_operation(transport: str = "grpc"): - client = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsAsyncClient( - 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 = EnvironmentsClient( - 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 = EnvironmentsClient( - 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", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport), - (EnvironmentsAsyncClient, transports.EnvironmentsGrpcAsyncIOTransport), -]) -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-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py deleted file mode 100644 index 11fbd69f4024..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py +++ /dev/null @@ -1,2847 +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 gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -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.orchestration.airflow.service_v1beta1.services.image_versions import ImageVersionsAsyncClient -from google.cloud.orchestration.airflow.service_v1beta1.services.image_versions import ImageVersionsClient -from google.cloud.orchestration.airflow.service_v1beta1.services.image_versions import pagers -from google.cloud.orchestration.airflow.service_v1beta1.services.image_versions import transports -from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -import google.auth - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) - - -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 ImageVersionsClient._get_default_mtls_endpoint(None) is None - assert ImageVersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ImageVersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ImageVersionsClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ImageVersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ImageVersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ImageVersionsClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ImageVersionsClient._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 ImageVersionsClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ImageVersionsClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ImageVersionsClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ImageVersionsClient._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 ImageVersionsClient._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 ImageVersionsClient._get_client_cert_source(None, False) is None - assert ImageVersionsClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ImageVersionsClient._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 ImageVersionsClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ImageVersionsClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ImageVersionsClient._DEFAULT_UNIVERSE - default_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ImageVersionsClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ImageVersionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "always") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - assert ImageVersionsClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - assert ImageVersionsClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ImageVersionsClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ImageVersionsClient._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 ImageVersionsClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ImageVersionsClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ImageVersionsClient._get_universe_domain(None, None) == ImageVersionsClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ImageVersionsClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) -def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): - cred = mock.Mock(["get_cred_info"]) - cred.get_cred_info = mock.Mock(return_value=cred_info_json) - client = ImageVersionsClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401,403,404,500]) -def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): - cred = mock.Mock([]) - assert not hasattr(cred, "get_cred_info") - client = ImageVersionsClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -@pytest.mark.parametrize("client_class,transport_name", [ - (ImageVersionsClient, "grpc"), - (ImageVersionsAsyncClient, "grpc_asyncio"), - (ImageVersionsClient, "rest"), -]) -def test_image_versions_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 == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://composer.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ImageVersionsGrpcTransport, "grpc"), - (transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ImageVersionsRestTransport, "rest"), -]) -def test_image_versions_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", [ - (ImageVersionsClient, "grpc"), - (ImageVersionsAsyncClient, "grpc_asyncio"), - (ImageVersionsClient, "rest"), -]) -def test_image_versions_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 == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://composer.googleapis.com' - ) - - -def test_image_versions_client_get_transport_class(): - transport = ImageVersionsClient.get_transport_class() - available_transports = [ - transports.ImageVersionsGrpcTransport, - transports.ImageVersionsRestTransport, - ] - assert transport in available_transports - - transport = ImageVersionsClient.get_transport_class("grpc") - assert transport == transports.ImageVersionsGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), -]) -@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) -def test_image_versions_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(ImageVersionsClient, '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(ImageVersionsClient, '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", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", "true"), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", "false"), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", "true"), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", "false"), -]) -@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_image_versions_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", [ - ImageVersionsClient, ImageVersionsAsyncClient -]) -@mock.patch.object(ImageVersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageVersionsAsyncClient)) -def test_image_versions_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", [ - ImageVersionsClient, ImageVersionsAsyncClient -]) -@mock.patch.object(ImageVersionsClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ImageVersionsAsyncClient)) -def test_image_versions_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ImageVersionsClient._DEFAULT_UNIVERSE - default_endpoint = ImageVersionsClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ImageVersionsClient._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", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio"), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), -]) -def test_image_versions_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", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", grpc_helpers), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest", None), -]) -def test_image_versions_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_image_versions_client_client_options_from_dict(): - with mock.patch('google.cloud.orchestration.airflow.service_v1beta1.services.image_versions.transports.ImageVersionsGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ImageVersionsClient( - 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", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc", grpc_helpers), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_image_versions_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( - "composer.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="composer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - image_versions.ListImageVersionsRequest, - dict, -]) -def test_list_image_versions(request_type, transport: str = 'grpc'): - client = ImageVersionsClient( - 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_image_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = image_versions.ListImageVersionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = image_versions.ListImageVersionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImageVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_image_versions_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 = ImageVersionsClient( - 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 = image_versions.ListImageVersionsRequest( - 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_image_versions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_image_versions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == image_versions.ListImageVersionsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_image_versions_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 = ImageVersionsClient( - 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_image_versions 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_image_versions] = mock_rpc - request = {} - client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_image_versions(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_image_versions_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 = ImageVersionsAsyncClient( - 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_image_versions 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_image_versions] = mock_rpc - - request = {} - await client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_image_versions(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_image_versions_async(transport: str = 'grpc_asyncio', request_type=image_versions.ListImageVersionsRequest): - client = ImageVersionsAsyncClient( - 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_image_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = image_versions.ListImageVersionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImageVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_image_versions_async_from_dict(): - await test_list_image_versions_async(request_type=dict) - -def test_list_image_versions_field_headers(): - client = ImageVersionsClient( - 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 = image_versions.ListImageVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - call.return_value = image_versions.ListImageVersionsResponse() - client.list_image_versions(request) - - # Establish that the 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_image_versions_field_headers_async(): - client = ImageVersionsAsyncClient( - 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 = image_versions.ListImageVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse()) - await client.list_image_versions(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_image_versions_flattened(): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = image_versions.ListImageVersionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_image_versions( - 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_image_versions_flattened_error(): - client = ImageVersionsClient( - 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_image_versions( - image_versions.ListImageVersionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_image_versions_flattened_async(): - client = ImageVersionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = image_versions.ListImageVersionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_image_versions( - 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_image_versions_flattened_error_async(): - client = ImageVersionsAsyncClient( - 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_image_versions( - image_versions.ListImageVersionsRequest(), - parent='parent_value', - ) - - -def test_list_image_versions_pager(transport_name: str = "grpc"): - client = ImageVersionsClient( - 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_image_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - next_page_token='abc', - ), - image_versions.ListImageVersionsResponse( - image_versions=[], - next_page_token='def', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - ], - next_page_token='ghi', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_image_versions(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, image_versions.ImageVersion) - for i in results) -def test_list_image_versions_pages(transport_name: str = "grpc"): - client = ImageVersionsClient( - 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_image_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - next_page_token='abc', - ), - image_versions.ListImageVersionsResponse( - image_versions=[], - next_page_token='def', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - ], - next_page_token='ghi', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_image_versions(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_image_versions_async_pager(): - client = ImageVersionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - next_page_token='abc', - ), - image_versions.ListImageVersionsResponse( - image_versions=[], - next_page_token='def', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - ], - next_page_token='ghi', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_image_versions(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, image_versions.ImageVersion) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_image_versions_async_pages(): - client = ImageVersionsAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - next_page_token='abc', - ), - image_versions.ListImageVersionsResponse( - image_versions=[], - next_page_token='def', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - ], - next_page_token='ghi', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - ), - 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_image_versions(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_image_versions_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 = ImageVersionsClient( - 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_image_versions 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_image_versions] = mock_rpc - - request = {} - client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_image_versions(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_image_versions_rest_flattened(): - client = ImageVersionsClient( - 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 = image_versions.ListImageVersionsResponse() - - # 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 = image_versions.ListImageVersionsResponse.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_image_versions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*}/imageVersions" % client.transport._host, args[1]) - - -def test_list_image_versions_rest_flattened_error(transport: str = 'rest'): - client = ImageVersionsClient( - 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_image_versions( - image_versions.ListImageVersionsRequest(), - parent='parent_value', - ) - - -def test_list_image_versions_rest_pager(transport: str = 'rest'): - client = ImageVersionsClient( - 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 = ( - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - next_page_token='abc', - ), - image_versions.ListImageVersionsResponse( - image_versions=[], - next_page_token='def', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - ], - next_page_token='ghi', - ), - image_versions.ListImageVersionsResponse( - image_versions=[ - image_versions.ImageVersion(), - image_versions.ImageVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(image_versions.ListImageVersionsResponse.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_image_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, image_versions.ImageVersion) - for i in results) - - pages = list(client.list_image_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ImageVersionsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ImageVersionsClient( - 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 = ImageVersionsClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ImageVersionsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ImageVersionsClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ImageVersionsGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ImageVersionsGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ImageVersionsGrpcTransport, - transports.ImageVersionsGrpcAsyncIOTransport, - transports.ImageVersionsRestTransport, -]) -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 = ImageVersionsClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ImageVersionsClient( - 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_list_image_versions_empty_call_grpc(): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - call.return_value = image_versions.ListImageVersionsResponse() - client.list_image_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = image_versions.ListImageVersionsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ImageVersionsAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ImageVersionsAsyncClient( - 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_list_image_versions_empty_call_grpc_asyncio(): - client = ImageVersionsAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(image_versions.ListImageVersionsResponse( - next_page_token='next_page_token_value', - )) - await client.list_image_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = image_versions.ListImageVersionsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ImageVersionsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_image_versions_rest_bad_request(request_type=image_versions.ListImageVersionsRequest): - client = ImageVersionsClient( - 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_image_versions(request) - - -@pytest.mark.parametrize("request_type", [ - image_versions.ListImageVersionsRequest, - dict, -]) -def test_list_image_versions_rest_call_success(request_type): - client = ImageVersionsClient( - 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 = image_versions.ListImageVersionsResponse( - 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 = image_versions.ListImageVersionsResponse.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_image_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImageVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_image_versions_rest_interceptors(null_interceptor): - transport = transports.ImageVersionsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ImageVersionsRestInterceptor(), - ) - client = ImageVersionsClient(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.ImageVersionsRestInterceptor, "post_list_image_versions") as post, \ - mock.patch.object(transports.ImageVersionsRestInterceptor, "post_list_image_versions_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ImageVersionsRestInterceptor, "pre_list_image_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = image_versions.ListImageVersionsRequest.pb(image_versions.ListImageVersionsRequest()) - 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 = image_versions.ListImageVersionsResponse.to_json(image_versions.ListImageVersionsResponse()) - req.return_value.content = return_value - - request = image_versions.ListImageVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = image_versions.ListImageVersionsResponse() - post_with_metadata.return_value = image_versions.ListImageVersionsResponse(), metadata - - client.list_image_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = ImageVersionsClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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_list_image_versions_empty_call_rest(): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - client.list_image_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = image_versions.ListImageVersionsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ImageVersionsGrpcTransport, - ) - -def test_image_versions_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ImageVersionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_image_versions_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.orchestration.airflow.service_v1beta1.services.image_versions.transports.ImageVersionsTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ImageVersionsTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_image_versions', - 'get_operation', - 'delete_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_image_versions_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.orchestration.airflow.service_v1beta1.services.image_versions.transports.ImageVersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ImageVersionsTransport( - 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_image_versions_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.orchestration.airflow.service_v1beta1.services.image_versions.transports.ImageVersionsTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ImageVersionsTransport() - adc.assert_called_once() - - -def test_image_versions_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) - ImageVersionsClient() - 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.ImageVersionsGrpcTransport, - transports.ImageVersionsGrpcAsyncIOTransport, - ], -) -def test_image_versions_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.ImageVersionsGrpcTransport, - transports.ImageVersionsGrpcAsyncIOTransport, - transports.ImageVersionsRestTransport, - ], -) -def test_image_versions_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.ImageVersionsGrpcTransport, grpc_helpers), - (transports.ImageVersionsGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_image_versions_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( - "composer.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="composer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) -def test_image_versions_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_image_versions_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.ImageVersionsRestTransport ( - 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_image_versions_host_no_port(transport_name): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'composer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://composer.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_image_versions_host_with_port(transport_name): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='composer.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'composer.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://composer.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_image_versions_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ImageVersionsClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ImageVersionsClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_image_versions._session - session2 = client2.transport.list_image_versions._session - assert session1 != session2 -def test_image_versions_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ImageVersionsGrpcTransport( - 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_image_versions_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ImageVersionsGrpcAsyncIOTransport( - 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.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) -def test_image_versions_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.ImageVersionsGrpcTransport, transports.ImageVersionsGrpcAsyncIOTransport]) -def test_image_versions_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_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ImageVersionsClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = ImageVersionsClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ImageVersionsClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = ImageVersionsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = ImageVersionsClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ImageVersionsClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ImageVersionsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = ImageVersionsClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ImageVersionsClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = ImageVersionsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = ImageVersionsClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ImageVersionsClient.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 = ImageVersionsClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = ImageVersionsClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ImageVersionsClient.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.ImageVersionsTransport, '_prep_wrapped_messages') as prep: - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ImageVersionsTransport, '_prep_wrapped_messages') as prep: - transport_class = ImageVersionsClient.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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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_get_operation(transport: str = "grpc"): - client = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsAsyncClient( - 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 = ImageVersionsClient( - 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 = ImageVersionsClient( - 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", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport), - (ImageVersionsAsyncClient, transports.ImageVersionsGrpcAsyncIOTransport), -]) -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-orchestration-airflow/airflow-service-v1beta1-py.tar.gz b/packages/google-cloud-orchestration-airflow/airflow-service-v1beta1-py.tar.gz index cce782c92603be305d7b3bbac5c6ac69bb35d89f..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 GIT binary patch literal 0 HcmV?d00001 literal 114688 zcmV)cK&ZbTiwFP!000001MFPuR~xyKpU?eQ=sF*;bL}=5NM@Mv-1PvN^|=Jt*qPaT z61I`MWxI!VtG6G3XU^>3zQ2;xFJlNKgnRcaeNN(TsZ=UemFl4f+>fV$yy_$(zVuzu zx!jtFly7ySW%rxMdN%RA-rZHdcvgSa`_|6xtIgeBZ*!~n%_cr}w!UGzk4C{APnM)S zX6&0-%JeR{Pu2e)efaJ2e|I=IczbBa$(N3s1pI1e=QjEGUiWrZ z;`x6r|I=kUmm%8^d=aK>Dr5Gul(RsfL}ng4iQTzK(wL_{paxo5*hni28=MZU{zD(j z`j5lo^})P)8OD;StPC0wk8% zY>r<6>H|>chclL>B1-lwYs+TmBM}HU1!CsLf~SIUGq%%!rx@^pMX~%1AojUq_0Zrj zP-6|T>rt3*J>CRy>QrTTd&z~+kru7S@ z6je1%VtxpQo?rTLn(;t{m*)<&jrbAyk-buZW*n*}fkIkF8a^0}Ux-6b9zgoB3>O$w zVzV(cV!{*OC9Z-W3+AVcdtNM(L?nbzhJwkd<%vjyo(NqZ#XR)brHB&@A!(~GKlJ<< zoC}sL67j-MRGn>EzxwICPGuWiY$Pm_fKf^*(R$6muh3Fvdj6Dv70#%R)O^M%?ygSA@AxEz5e#-R_YeX4lq#<&Q$= zN>6kqfpjnS_Lxz2%VK!6o@}$u0vrr4*$<@B9lZUhsuO%+=9Q&T<*>`$)W1Zh3S^}Y zYEba68}W4Bg{~VOTEzd*lUIrLDAbjoA4hKNM``l$7Sf7((o%6<$bfw$51L>kGtc)t=(5! zTXp&Oc3y99KgWMh@x1s8>t;!;>>imXW3H?htn;!%W({V4k7en!^DUL2d|yV(*q_Z) z*4ylD=fTg>(Z2NpwMWpAFo9plLKVotR}3PKkSMQdvtP8EV?BG5H3^_$sv52Dfq}xj z1z)mIrezQ~_0fm8c14tu`$j+#1wId9*9(_qkk~-+4}(HZQm&l63!33_t8k2`ieP%k zH^DVsU0vB+5o^nM28*u%lkU-Q|L}Np*a5++$@?&XFK4m%?+hN=W0NK05$JJMa246%G#Cv> zZQ%HIIR5vO_ha_!;N82y@pyPRVkhs|{>kyda6CLY#@8D*IQ|Fw`|$Xn%>-D5Zp3v& zu?P|A6B~s`JR1p7BYlU#S6d^_zOQ(fmm{L zQ0T@&k1|F)6we|aCnEorN&W^W<|4%B3BylbNFELq`6pryYZ}W1OP3MRVTzlB5NX0b zg@O=7n;rOW+D7LI{vSbDh)z&C&Z0oH;Kw~N1>!jMiQJ}k)(|JfrDCr@^Wg)qp0(Ko zG2mHSLHVgbcrW9<0;__tTCDScd$}2Nfh7pA@SgMHN??eDK4xSq!J?w_0b=ZHm$Gu93W8?+}m2 zkW?CHLbGYggG9ZW?y0^&xdjsP_suhKkmACG8P7lr8^=6MC_xc%6XLV?N8?ISOH;W& zes|=Y4&Dvkj`j?@py+2b$PM%uFE`q3BlQ;o%%Rr>{Ef#`zR^<6-yTBe51jEyfrI2s zDB2Zlgzk@mDI1v6?uC;@vzU8gV-G!5f_Cb}UqH1T6M>_k)vh#FVZT#tK^Pz|)3}bS z+LY)5A$AA{hktQ4p<5Akgu(Uda5% zA?YO;jACIZu2ToOy>P;8F@ZAIyMt|@H67Ym`kF!Xra@N%lq%wNU zk-{YY+ z0r<{}Rwndn4pI}69LBMP!Tq~fs<&31mKW?$#~KvGaRwVRmmbqDd#+Z&DEdgHq+Iz@ z1}erus5C*mk;MoUs>qBNGQ6>@vXh~X=)^TF0mT87g;V5&5&K@7nG}VBjf6r*#C%g2 zJ6b1EZk7kC%C2A>gJ=O|fNNGOB6Uc%K(>I$G9p^lilbVNEX`<%ioij^m1@?n#2Eo! zOgzr`p5hHf6-{m%N?U~n*wn67VDqPlua?b=98k-Y_4}+rQ7GnJL&XFa6cgx9Z%E`< zv2h6w1aM~F5|m#P%k$W}%{6Ye>q$^Od0xGeEmi z#Y%wCUeQ}ZUlg^h6?Q8c36;2|=q>BYou|VR20`4f}ULY8J$|Z*ZYi8L5#sL1L6SUA4Xp5vZcb zsQKXrA$iqdAjn=d*HTJABT5j&2y;H1H5(g${JGJvDVF1Dlk8p#W{$veJcc{*O!Ma^ z2X2J!zb{Md2lNZv$J7c_O&|4`AVGtf}c{VH;mEWtQ9 zWGoCGKXg1FNsvj->{I+|%E8;)s$S}!w9E?nx8x7tLaWG_4l|#tSBwU!jV^WCYA^}u4jNtY;G(Gs zu0u}=z(7t}jy?h7QdqI(w1ostxePm6YBDR?0jz!2@k8!bxF zr*$Wj#4g4=waLXaTUAeeO3A*No$%3me*=O~t0GcPsp3P^SO{a|)MA0NkX{yuCb}s{ zZuA^*1a4pYn3>Irdez9-*BdxQhZ--@QAm(%L*`=gl#3ssxKbRoSG!XYKZRRbFO(3e zNHYiwpn(69@{L?nHz-ypY@MvwiwnRs^+(bl$K+g8SmVeG^;sLn&myF>Uk@Z_fZ69z zde2kC>liV4MCwkfHPqi4nO5n6Xs_0ac52famdJr^5+m6KXqux!X~!Ym+HepUW5mve zZm#4OYj>>P$y;UQER;sX<=jAeqt=@-E&G^8ZxD!NQ9dZL(X<$t=p`w$nd<6IYqRZv z`8}=%gSsi^E97~6GG>%T(HP**l{=wwq)on#JhcT;b6j!8SWErtpOXf$bQA_X~SZwaOH336GeKEzAwwlEa5!-n`0X@g#|!bF{^31{|Sm5ia9zKL}f~_4xje6tGHPJd#A$`ok&J=bP6Id;EREAJy9W)Z{EU2v6GLcF?xBGP; ztU~;vwv`7jcR`oc2KUtDE~eD>6Z&aZ@~9I`1`?CQoA4@8sd|$ZO>g3DQR27Ns`iSm zZo;WOWB6-RgHN>@vDw%&o6Twy&VfBnGa|NeK&h0BC?KWN!c@Aq$97nU{RAJ?umr;S zhqc{B+tXNjnaWqXBee_PuJHvO@`ZEt;N@3w!~El09#_wb&-Y~f|c?ro_O^-`4d@|W%W zWhZ~xMNel|76&AY;(RZrKsHgQiOZwD-P$ZQXMSlZr%MY7-FzRld;iJY_#)#$dcP2= zz}S&H=4+$8BY|{KO>tk^YL>6yfmIH*m+d!{mu;xoT7k+nnF`cYEozGOw451*ikgCA z70-O@os`_PswrP?cNSaI%_4y@CAQkWO=uWRqj4A&CT#_mdey-+VeG51Ri}R6{I<=` zXSu3VdDoSJ3};RiLXTNjlB&zN-zejbMzz8bP>-PBC>5!bkL%ycQ|qRQ@$mhI2~jW| zObs-&kAM0@9cO_L!~pu`rb*qll+k`;7}C}doc18|d^!b07RJ~epr~XGdEi3;C!--E zB}~9ew8Xa|X=DP1+=o_M!(z>1zF3eeKFYl_n(E`{_lKmn?FWL}uOHgr+lMyz?x78~ zHXqz#>%lF0)fOjexsTvS>bScWB&}~5$B|Z{#}b~IKuAO4P~?^7_*i5vaU}i5sZ9Lq z@7Y`K0^5In&&<(s1D`8&KYuaBicH6ZrNBZ~JQtHWZc^4(U0V*4AAQlLj1G`gmTZ3a zBPZcg(SJkBWo_%9mYP04Pw?E4|I>|(M>zfeIp_a(UvF+dpZ|Y~=acf!LO=aNCHRc{ zAFp2Zp5^}(&;8`Da?Q`yf``lh_3NG8XZb(H^AP#3TmibbK0H|dz258R`(IDqB|fYW%{H8SNMEtpWB zBw8St_<^75o9X#kg&$}U!79$Tt5f4-g~;6GSG^X}y|`IxQ*jP5NS2}dmI~Ml7R7wF z;Ct-&1YG;&@SSDo87f$Hgne%z-d z2X%d)Pu#qINO!lONd}Exw8~dzbD-Z6r26{EtyL+?-%&g-F3By42Q_Rk+YT*V7bKbQ zeA_?+t3K@okCQnM>^Otg+j_^qG&{)jO6$9fPKu8)P8iKaM4z`}$lG4UbnPrQ7xv6) z)1vmBI-Zt@+iKN!n+|Q#**MP>)S+$6U9Fp@*+_rio3D4WOmFNsQms%XcYUEGTI7G+8xQo25q4~GQtBTj2U+-B{y2x710?4Z!`Kc72~7P{+x%Q2$YSe zHPnA1rM4Aen{dir36=8i#IA-*c~^&(GG(>&U*q}uoqf%I=(^pC5n^W--Um* z)zlY(r|!8uxM`ZZh_x+q8&u9ebHTvaT35uWqmS=8bOLn3-HZG{nz`LDX%G-1GI*&* z8=rLhO@CRIx)=t0JPSy+UL^f6)yGSLZZ65A(4QbGU=}H?L;<(5XtMIQC+n4uob0Cl0QB7G?2ep#wq@uG4>+kIsv+8yV?rKcEHuYXBlr>8w z{FzcTt*9z9rqt6`*C%X`u5`*GE^4zs8b6<${Csri3{Hp6dl;Pkqv0V;!~WsB@$k)X zAJ(C<2dflkqVZ?tSoD{Wt1l>hMQYVmjYlK*>vQ*gm}C(}HNvY=ov&+X=;xCCgi~^G^=$T;F+zlQyeL=cGvI zw5W8hgmm8cTu#14a#eUTVqz#RMf~VO*I2($>NjZR!4+R7kFTK`?W0pmivO=Tn{H70 zfQhs=L;u&CQ?((M)9GC4<$0T(6Cd@2($atUjM_gsd4J%nM4ZZuA`PIJ=PQZ6!2iGO zy?KAz$gwDzzx^q2>3g532}LblW}+PC97UEVy76``dFGev<3~XxBq1URh5#iie*W&S zs=6EK6$>{}GMI@)0=;+bU0t=Qi=U<@C%7a|2m=b;g#Dl|7XVp}CW|IpzWP*FaBg?e zGW_2%AOzf&M^maK)LEKxPHOq>)8$~?9A_CTG&MJ5^H*w6Ve<8rA7{&MjAo<7Rh=%2 z_dp}iFtubyBqp*do3(@}_rBv{0@ z&tjT_=qhz3#Wk<4u|y)aiblyh`j{l@C=Ii5?oYHCFM1$Km*ohrvQ_dPwOpIhGWH-7 zj8bh@v{HEp4Bsntjm(ZZwsattP~q}34vPJoI|3cT7T%Mz%uAl_th>LGO;7+mRU$Gz zyR7w>`Z2aTW8*W+!Hd`)eQ6kQmXMZ*Fhp^$Iu-IM62<7wOX(O3vyi}4Jk`9{ZsLajs-LmyXYho`yOV4c6T>V&{&)x~Mg4!|B z!aO@_LRa(o=G28O%Unk? z8P7>4+9^AJNM$zbQ z7)|5D>|s+5gO>fvK|vgyIOj>Af%3nIihPQGMs%R$1E^4Vn3OtU{4X9sQ8dUyzRlQO zc%iK%0V?fyh6|Q4Velf^#Q}Z`#R2`)pr};)j82^>3LNkUc|p%uyc}`1CI(AkiOwTb zKs4Ok;0|`_A=fsjaa7PbfTk1}%MLwmpyADR_+P1|88@Tc zTKA(Yu*tqhQH=a-6A?tjPDqUs1sp|kLv8OjHZF9MjISutV4UEQXguxp(5dh|==sbw zl43j|>y(-thB57qXnV9pL&7DLds)rimER?^N?UGJT$ry66m#!B?EL#z?|GCjTx{3^ z=GlpX2Pbr391YOdQG}aDS5xU`HgDyvf6cvF$zyRkO5+Xs11}o&*m?Ib9EHQ_P?Chi z-TCN(HzZ&B22hBGfR}siy=Uzmv=&~4mjD)Qds)dYmh2Awe_~`_O z@!P@^^0Ji;G+p5u*zK~=fz3v{vH5vtfA7l|L9mS8yuWyRIHace23B~F!t9yj!F%k_ zB>RmD1l0(?T(nT~bCUTK&-{$yr&yLoFSa9BKIbby5sBeR-*vu*pBWF7ig7{59)}2Z z$^xujgqPC^IW+TS;!E9BW%kW14isBN3RtMsxrn9|4pLuSugQ09vyJ{H=r4|eSTRho zGy+?T!B_Os4ik(Vd!~-)47XQuCuuiwNq=dWVC$PTB{xb`WkFOyr3^eWg+v{8UzpT^ zc2#)(a`KS<&ZiB!$8a%$;6y_0Fr^UM$O+L4;2C zy;TwkOA()z7UFqE)U1e}^P?zVjX7~sL-ZA(Xo{YG;$;hqg=w|>2z5H?mxM72A;@7U z5^mZsIeAv{DNX)%?myA@jxIDzvaO4o#C2e`vqRGAN@cMU=~fR_%RIS!lVf%mZheaWm+dBh z(3TIMkmTTKGx7%YF~3ZM@D(Tw3X$LQWr4PPweTN1Wuo3SC8t6HPVaJBBI`lEKdKXm8?musnroI?< z#GMHZDGI&X9hMAY%(=tzE3tEAL`q&j)eKmo5@#QZVLh`4;wMwhJGvRmki0P%zipH} z2DfOEzicy9At&{q-$f~|OVN|0h}}Qtaxt$5*Ls1>!Pl($V=zU$*1GOY5yv?)C zXgM1F>2P?rjo-Ife6<*ZS*;HrtS})Q`ub1k@iF#XOvKY7oq%yXlWCmgpvhX3S^01L zkkUeC@3UxpO3QhILQ!dzzfd(#;KCl2$ zZ87I^wVPKCLaU~pnGPtQdWV<^lo=6#Y>6`w*-mg9c(;@cjR{(q1|qoiKt^ikaa`Lr zZCFr@vDnL`w{KDbi^R3igHb0}%Rf(n!P+IavMY*~mpGZw%HsLfsus5VfuhQfr3t$x z%T2_}O*(1HY(~P&ln#JDXtQ~|=YT9X(rLv1nuh&040YJPy$S}`ja)&`0Q-$@HynjY zx69Up=UkDpA+QI!EH~SkTbG5l)oif*@21hGOI>mTIq4^^w6G6 zwFATD3ByFty)jGae@&yrN0(jPjBeO>H;6`_j>Hf!t552<#_!!6zkB^&t?X7twQ>ML zJ`Y2yjiD^)q9HiNSTv00-D7|XyjAY9W=G+LTmo7YpdtT%NE6!rNpGWzHXX~ z75H5`cvTfV?KMqUBSK;7fo5uC_<@jN9W?qvh?KScg&5ykI6!&jfJraTAfMiPUZP<> zua6nW%%ajPdC=}oW;s@vV-;NOr30+bE0jUZ9+xHm*n@|xx%-u5Oq1X>*0qfzlgDd|gj3#aGNaC!%i z(q)$8vi!Jnw!Q3h>^JJy$sDH)e1Z12oTYu#X1Rk`hdPCPJS23HG;U>qlxFF$d}n#Q z!5jmAW}vU)vtpuY?YcaPr)pNZTQDDY9FpoI%Om2}Cd=|(@tNl+M(?vU4@f&NkC1GA)2th)+qLq4hsI?+~9VJS44?&r8I|#ZxSRjiSBIYA|?#dcq=`i57=PbaCG-GEKd|c77QHfFB1&XPJl9U%$j;U&uB8)Jp`W^QQ zW|_qv;u`VDX%c#7f{Q51Y}>ONLY%?O6xT~*1kw!+>1oTeOKNmIqhI#05)V&Ep%CHANSnZ@7I=Gu4h@#fvzBKIvPt|)+1R;JWR-g>4uT%& zrdkYqON^Fo7PDxOOM|J!5RDuFD;9Zb$J6vvc`J3YUAvzy*ZuUKwq`~r)b&vPAFESI znM<%r#O_Kafuhsl+&l_(c7%%A5hzurqIkA-J`@Lujs2LY*S5C`5^XkDY zi0QLQaOqF_nALv8GL*vftANhU*Sb8V4yxIP1eUtfK)0pk+w z2#&p(eGl^2-=3*qp?e_m!fBge6`q&6*cN-kidVaY_E2&CTSbdc%4m~s^QPE@67-rG zJEf|sI?H*oVzCgdBTT5H*J4|CQjRt|YU)urosd(K&aypB2g=lSs032EpMaQ}(nBLk zE2}9-@MM)MyFu!!q%q}{l5f?CWF=kZ<4#kRd(7o#>85ppW^39AvMpNAawQbBUMMML z0ctU*tQ>$@fGfaMcs@;n`{rVm&;!<`1U_VN(+>uvkY|;wbn#+NRTf*vn96N-))1lU z&UTpx#GIj)xbcRyrKBpUggq&!aJP)lja|Hsve)>+mZ!dzXMej6xAOG8QdjUn-_0|k z?JVa09T9-5U@!(kzsQSsa=XjD$tL&29xv_^8ilN_OwDwpsCt=7Svv=nlS6i5A2UY< z%czWw$_<&XQjk$j|7rqged}7a`jYZ;31Jn~q_DaqvD(9orw60GK{V~RqY1!C4D-U; zZ9kk`45Hh%2+Mo3dmbeIuK1mbz%+n%8G6}Pk%JIFt(W15`n(*fn8dGX+qg8L$%ZTo zZ|r*;dStte@6w_>Mpj4OyB`#&g@HU_ppbo2oKRcpxte{~?7L>)tB4w!q&b)L6i}4> zjBo^1`q;nWZZvc&l$*+oTzL-g&iGb#P6$L~5cz!-?NLm?K7piA6oPTkqlqyT!fw+# zajSes+`i;))$jN6o0Dh@w5L+8M%Iq{!pzxGEvz%HM0d8T*)r)QqM5a-=LUgQFiKks zE}F8a%cc<+leRQ+QWxk!tt2ueO}wh;Qv#)h4U-cQ^TJe``{4HWRvY*>!s#~2zFX)% zf@Ex?^`tC$5?wO^&9OMToE9q_*V3xk$Ir%0SRMfodcJmJ5M8@Npg;a)&>aM$%j62M zY-`tY26kdM(a0tsiJ#W#VE?CaZK<%W61=0Fpw_GU5 zv?z1aHDCmx42L9yGW;%Q@qQJ=;pK=z-(zM?Sm^O2#Gj0&GG|3fzscm$!9Yqdi@!A5 z3)s#y;J7S?Re}DH!^ZM31C8_ICBTHOijSE^jLCDVd;Rii{(M_5YbHssfG5Ia-rUkpOiIYoU4_zFl zTJ-bI7rj9&3y-mlQh1#~m1R=t0`XLo2oLNn06M$&t)zXIlJJPCE$?CqyA`xw(;p>W zjk(%g!UmdL(+tqW^3V3r$p@$*z;!r?{fhu&FAWjKW9Wbn9@x-eaL190)=Hph*bdqm zhA~xu&}0;O7kI=N08WEQ5e)jMPr$_bE$=o0I=W(##S;gq^y)#Qz8lFlRRq_wPOK0Y z6wb*N_b2q%%Y$1g(X?~BH0e`Iq34}aW6I-{l3k)^mo>XA$u3PBRQokd`P0as+|fUW zNPRUCcSa6t<+c8;A0}(XaUU_Worj*8#}RDn@`<2Axa!ssuHH9$|iMTAB^^jbZl2qab(l$@kHCLpQ#x2Z33XNY6)} zLq%k0q){TcvN1xp@Za^VyHnm_w#^$~x6nGW#rxeNQ$oCvZ72u9jsl4s%TO%1zWuxb zOXm0e#NYTbJ3Ufp1Sd4B5{+td@u0{>Ir*j*sfXA~eF*HpCGkO5ohDaz(l7$QccmL}T2edH7?BMdx(@Dcqe&kTU`ksrf_JkX zq}cR0W1$GAeC6)Ji8U?`U0GWm^{&Hle8hlEkMQ;05^A zsy7KCNKl=HTK8PlH&Px1tu)_vgL ztdeUA0QV%d){JN#Mzn^ew0q@=73_FFI+LvVBjb;A6Hekc_ono(4->6~aO=!U=kQPY zHAu=jr(hJJ+B4-xI%?B){C))uCvqr*GB8CQ^K=^aI~(|~^)>LgBygf(`vhON4?i9q zoF2dXRYpPa&2)irV9f(GmKW2F<)6p7wnm91Ad0sU3~=N!JXi}NKu|#mGOPs&K#aw3 z!-%ZSYLHO-=B&4G&K$(gf%>cU%5h?78TnC%)w%s~tfQ%&acT)+aS}o~>%lsU5ykF3 z_b*Mp-{XBN4Sf2VdRN(79+5KZgUxn=qEUk8@ox08!MKX0;Q>qd#IX_I!<)p$WWi)5l5$m4H zDv7akwFks{dqB)Zd7S9FS}%wktSTdPnJ_!ICxl}}wJ$`?sPEYuVp-h0*sWn5nEGSq z=R`yn#nk7Zow?o!E_$2qk6_lSJrYU*;lqe&FrOSUvkqgpDXasPdc2Mb%ZPkZKp1Lw zg_=gVXv8ArCzlVyIuMkamJ~=5KcX+gdZ{v%`Sm)uHki1rtYE>-&^0?FTc`LW<*>DO zb0~(va#BF08_hGD)qZq`hX+b=??Z%IOJ|5jMef&y($7muYR3q^z7-&KIZPpsXOq2B zN=1fF7UEciXTiQV{{@!g?J;o*ZYanI8QBW}|H2?f3k2>)tTBf;><8W8;sW8b<5hwe z+X;eR&64WJXjyTLGn4!*yZjgPk#P>HLSh#$6>E~v)i6TQ)E%xBHB)(E=g^o zX471`CMWY7EpKB(8~COYmq>gg0$;*|r}OQ*G)FEJP~~sR#x;kvU zInGYGq?S<9;RQ*deQC%aAdN~VYGKhWVeNwwXNcw{(Mb{0i)*G=GrgQ5HPfq^-a1cZ z&Z(DVdg2@5sG#s=SV@~|NNG)hKGQ0&D&XT$AjpUa1f$EGW{^ii$N1yX^ zAalJdWxi?4ZGSutM*Y;2&(wvu2E&RkUWbtt7~aR6u6|6*sX189!DK-{M1?Ort8Mpvpq;E%(2o2-Icm%#{=CPb4h*8lc+Iv8y4 z?*9DzDUA#&;ks!Gz%GEX%;ReZ(zEes+uv<$C)VgzfQVe zrAxt|#(isidHb#4DV45cv;R=Hjm%AdD0yJCL@eeNUpG8IKu7yhczq9vjB}_*eJ^*t z@8!;i`fem!?akagTqvV+THto>ySc70)t7T?cDYz~c|WPnT;7Xo!Eqlkvz>>Y<=&Td z62bfnvzBW0joETgv;OgW=M)d-lI@jb!|Oy`9`C)`MF;pUq7C(>*_uquBhyqPCXSo4 zYe7?fcyf|UGk(N-v+Jg1%*eRc;r^@z!e)t%Metg|wJP^OqQohEY zZ{b%HVB{+9eBPkHyqz!Wn?-qDVwKxlmbS{)L4}>1t$%69ZT(jSf}$~$q@eX(<`VRv zq;%GLuta25+5HE4!RWH8=gC$Xut(%tdfPIuK7+&@y zV9k#C*2OERB)--jF(sg{q%2VS@M?CO*N^Ul^1w;%8XAe#(g)@7u!D8r1as4x+T(#Q za1|I`0@Iko$KWHp1O@u{;QS<*+ys+c7lR2a+`SFXyD=57T?`)mnTfgS4~4ZBx)`|O z`2pG_%b@jrdKj3CU3(a;w}-)enD551)p{7@ph6h|$O5)=I~X{IRQngyyz(*o7pw)l zeY~7@9%`2BUf?8w`R)alYPEYoDWF;ZW5YQ`gN1t+tOaSQy$i~E7Zj0(+Pk2p68G&~ zuofhxrY196HV?0Y-u0*PHc1|FVX28%IzI{&BtRBJ~7SuNSal=}&ubIP~3yUdeUc^raTx zOap5H@;yN5t~51TzRp-4ls4tIL<4OZh$ywV1*)tS0broCasg>stsFs2rx)d}wSIIpl$md7-2L`UX_0d6jTzP0l!9~b)^J&V)S;G1d+xk>two`>t zgrq)SsA;;h`VgR+_AKb=;UtO170w-EC|(~r{BT;iZQIxA#K8u{HdQ-} zyZvYsbWSJJKpj17+jyFEK5wuuB7sY}^ME|0cz{A#Ir^|-9oW6ab_JMkH4XrG+ggV0 zHBMRIcUk$f?QU(5UvGo_y!0v$u~%z~&&9toDu)$(=QhGShgDnPYhHi<=J!K)K7WV?g9^syF%++j&p(_(YTNcTGCtdY*rsc8bpp0Q zQ#bQW%XuLG0A;Ll*uP>u(!GIpJu=(KRF!;^Po!#d@p_w!=cO=t$hul{aV}1k(F&~K zJGZ&mIjq`TTyy99Hy6*(!i$Z;Yr@HECZ5B@=Od802HqUHns4B>R;&%YC86)3*=FXJ zMCQ;|3(ncDOI) zTA{$`{LZ%KNNT%j%>f^2YBD{FG$CKoG=ynNrZr6wy2GElyW{C+6|2B_FXta~&A%seDpfxp_ zS&#wrbpU`Xkn6()As`8ZIM)t(fps#nHBM{Q_RvSK={fg)jY5VxVcHgS4EhDEx$9o` zg6_XDS;dC_#G2VT4gd!FYDM#zwQ3k=oPH9F2Vu|e`Zw?d=#QQ&BhP?ah=vbP_Nzdf zRvZDX0I2L?&~#8@shsWbWo^I&DQdzAY1T$^0nQd=)d^X(*?PUr)(fG|h2&+mX6#}r zP)5megY?{1?fe1O#_d|<@zx^_>tm9Oip}opBp%h0(ZiOE7QkV04;zZOQ~sfYyLNr} zPz7Henh|j^(%!tvWi%@g*3=$n9jo7q z`T&tKRq2MK5J&xO1C|oH-PlKIIzn8Jw_|@e9t6AFgQzEbnCQvg#&@HQ&kbpn8egbM zJRHOZ@vqofZv*7)i|`Vjf7`gc4!XSoX!*ee%Sk`8;(h-TMDiGLFt`Z6VlnkeR&o^e zp?)-_S?uooyaUhT=pwm=nRTUJL07nh@c?96Be9t-``aR$g0f9A^kbg_d93*Hq zrHy4@rQuJ{rPtXnX*(;c4VgldCSk=a?4lv+{sd-rdm3vB!HG zU$Ea`aub5y=J&+1>5sAzB>pAq1HVXZXFpk+;kXM#PAt+m0wwQ`7I6w3fnJ8d8)ClP zv_%YbGgT6B4)#f)LEd|53E8+~XEV74BsAl_h2xv&-Co$AbkAWj*YZHLSC%nYD!bnC z+TRI|zQTI-0Yjk^1VP;Bpa1j=p$Eb!F5l3P|J4OBrrjcdZIL2>qf=Z7e0gn4scaX- zOEJm3>iuyP%5`B(jwQ3dkx?gm5A+$TXehPT~@|{>Smye}!mf#`Uu&Y-VjCncKqd)z; z$N5e6^OD#7JtFcDp4lfkLwcl@1;aVY~rX$A2uBl9SQM5uK11=7VPpAmu>_Lvef zj(8vijR$@PSMqO()~S@zV6|U3n4n~OX9I!ku5teO(p&Sgd}utBKyho*? z@m3PT0MN@0Q``P5cqgH4RPS~R~k?Pq?+#$SK4G$nvVPWqk(@O z448oaJ@rQjJT8!lIbK|V-i(%d(xyc# z$T_?|&>1uXu*TqVoA>uB7zA{xcPHEuZm+`L6`hQZqQn~`hXS3Fn{62WXB}r_;_aOT zfp?W8<9L62`!Ydffq8{*brC>I%m+a58BP}*mr9TLY5az*st^H1=VJTKr$$F%IV*2)bQJE5i~`T z4G1;z%OL6UQLxtICjHrz4@-XyZ-P;3qhsqy-X&uEO~!`9giU3$C5};jZxF@_*}bIp z&~%pCM`B?pw~Kqs$`P7XgFe>i>ru^}0~ z_=s{FR>xqSpwgKP1#LoY*=2++^FhDwojnD3^Dl?~zW46EcliFdqmO6adC>ExF&Q!^ z3@LF^=M25henPk9Grl`GwpeKwC_%9Anax(6K(gt1K`MpE*WB~b>t=;Ri#=SCP8#%??A&t6Hr&sr3`GJdat4N zz(*WRf}tQ}%!nkcM=g&LY=MA)V$gIxMf6iDDD3*hU?F_XdcaJWX$)J0W)O}M&C>}{ zcaE;oC2sL^1ejBf8LW--#skzm;DVl}12n>+%UXu-F`g_3#C|&7Yac*VA~(3O>1z$v z2rtvacN%7k)|Sx;v@z4eO@l~C9nt}|{5l;a)s^kdY&7YH1(P6i5J1`s>kJPC?B@@Y z&ZzfuI#viGe}%IWl-+|ZiB-4ol)b`A@-v1oJCBv;UbptYjbCP58WwPCH< zL>{KJ{V{UzrnM4&zBQ;`V_$$=Lo@}C#8-GK?Hs(2etow#of?flg6Mmb^0riZQSmch zC=p06$xZm!kWE&KprT+GxKW=8SukAJHss=_5M#_H+dw6oe1kUC@-iN|D$0A7RZoG_ zT`>iLO&Jr!Qw^mrv;mm_it7~;K%-rtxzi&0kVDcwQ;T0VE%<^T7-}9tX4mT^@nS^HRiZ)Ybh_|F*hNo_jx3|3+2C+)Y4%bZ648y+_0g3>Is-pEwOPVbE7 z+d#x%6wQrKr?0nuQ3B)qOFy7in>BjNZeW<_irTsILOk%Yr0QZnNnXSQ;fA)wjogFP z(R47N)22x;7=zx3hpWtTKw?RW6H~c%+|=9Sq$EWQSg7=S+?Eei0dkU4@oFLGs?snz zbY%c&ranF*N_j&%&dSPdZx)^mTO6-9=b|Ix5WFGiNXz^0jGCGa!jG#i$f)B1Y#US; z$Hb^qk~6pXUC>SjVkt3!)?i??{~%;BH^#JBW3!;aa;pt}fPQTQJGKD$a$z0eDYC1d ziNv(vhq&8-l7?}=0SA>|;9RI*r41lmBrtsee<9Q%i(pooEFP_G9 z65^}j9op0Nm*-Lc4&G)H(%!?ECU;%t9^xqX{Yf6lwXzbmR1PySie@6i2N0P+%#?DD zJ1gnz!^(-AEO%4kOIANI_hw3_BjzIGbv`RA+(bPH=yd~z+Rz-Znhk*MD}Ri=Q8a_TBiQYqb3lC{XNyaGdSB1Z( z*hV{0gG3!|0oqyJY;C!>izDU}Oka9F0jIhQ86rvA8b85|T2a$G5A6`F_rm%UGrAx& z#BY%}AZ06mI~A-~UI`TV)xz@?8MN*V7fw?>rXV^;C{lJdwMS4vP@$`JU0Y(+<;1&T z#=o7VHisxe2#^@KTHO}|Fi^{xttXh6A?E#U!6H*E!r0P{nPh8kidzVZnq6r*j7r@{ zBX64Kn02}p*2u6W!{Ww0iD&k=D<#ssaZ8Z(gq`F^7fi#_WnFCWqAYLDtR*u&Aeo*Q z|C~>%-94KY1Jpa6CH*F+3XxP z@B0p}v$mb$Yh2s<9PZ>AuE-(#d_Q_=gPevw^>QWaYb8#JZXdVlm&d)++Uuk}HL)en z2nJYX?1un{%xAxsI`Ch=cmn;rec~br!z&(2+Xb^?C1KWuQ^M$TS7NGK*RKy)R7NFw)r6d70|G9JdygQs9IKS`GL%o_U^_yLoQo3cp+GgnL zKv4q(Bh1bk-_v!enP)OXcflKx3>B+Nb%<8Lkr2?d^_l~4xFQ^CZy^ZeKuy-)){F<( zfvDRHeHYECTXProX@3}pSF6kkF(+uu4npuEr{)4}kWv~&3~y2P`Ds{sgePZ}DWqd6 zE>$9-bbvWnn*(FX$)(2LEt%AZYO~cD?4TUZm_d<0uKa@Bf`GGBTdmtHw(?aSHUz zI1xQY!gba;D}mD~R>gxzvoRCqSAI_xeJq;j#J?8HdIy%+4Re3UyQZ!sUItF@pTS@j zB?wcF=`Gu7)ZL#hvN`}!uk52Qyk-p-CxPKWyGG2P#t=R;DMyAdN_Nue*FP4!2#LzF zE*OHUjqVbuPd@U@DdZDNkVA|i(3qVBqQ*|mC2bGEIBF4Cr0tVi-}wkaPThn@$3Yr` zL=O9R#y8yz_NIg(*^7KvJFW;E{4n$JZlGb?sz`$0Fr=8zN_{~?I2S-W{Liz;P-j)w zvkUak`~Dwn)v7)2($2yn@TBtZ`Y?Fu?ox$el#9bK%s70RI~RNb4wZN*H4_-{q0n1kQDcYH zV)eK`xWe<+yx0{A0kD+cl$T%~i`RHftM= z2f_t!_du#Y*L8y zrh#v?MpCN7GJQXc-xp|lMr3`O#cEcY6DY+8j;)PLjV~@qqhBfDvdIt3jibzjbaGzf zAjXvA*$S_LKpK%Bw4y-6SpVS0A|bHMM58$p3X^GKC$Bk46>2|>goqo5)d-yIV}k3~?T$k7aJxJ|3TxJilY zld%|afP7wAS{E@D6&S{}x-E%Uf;}RXQ+i3G;*v_m_{Alyl2cOoS5d{RqOwVOS)=me zKMj@tqk2+pV)OUZuciOnmeRk@C7rVF@IQKLXx03;JKi9!)ML2=Y@;$NZt%jqJ%?mQ zjw8bcWy$F|J8oAGV06oo&lvei(X^BrRsGppw-x=&mghSiggmrCtxp9IpHaTTKPvv+L9 z&racWAt;7un~mJFzudR7*~c}{4wBJ;G8Y#4U>SO`Aco6tv)^4K1lWVS22 z;p$xRC%@NK~`Mo5$WEzEmf*CGkYlAJ?qYj+8W*J(OEEl;jZ;#T>%|1O|fA| z_*vyM*qxzKQ5*Hh@x$G|$ZT6?z3d8#6z|X4 zU}Z*8aP_=W8lG;{#-P`K?klJ7f(=x|>JBx&xW>m0;2IsLGVNq*wB*)NO?jvzHV$|T z7Xez@pqJyc@C?YcUd)S`mv|W^LS)))dyRPW>e@86f9+{NT{}MeqB>34u`dv4;h9CG zYjqW)O?#+WztO~zkRUXNIQg`VO_zFUIdSU(T0y-SjA zx76uTAz$D1^V+ExQoZp$OZ(cUFsFuq`sgN8i`r6S$*UXPZk8HA<9NRDUMD}gKfY{E zft9yrby;YSMUolt>NFY++J&#FxHuW@-C%I?(45)!@)aNUg?!oSC;P#Wu2a7iFHMC* zkZE)JICAY!D`Cj+clLul8FBaagEKg*hxUUb2PZt)_BIb2XA}IX>U#KcH0Sn2YA>{- zjUV<029+_-`yxI#_WWajXn{)j;50uR`SJRzV}Q(f;OYQtJ~(?TsHW14mm4c#cK+h9 zyLlvi;HTs$>lOV!djY$2)q|jonNe{;(^mZ^pvg?dpDmqJ%$HLT_^? z&Dd);#Vab|YX9;JMd@hq&GFzh2*{@|Otec$_2s_u!xAX~ToBJPrf=n~%JK_}jUUZq zmqei@SMTzDYUvR*Tq`!x?$S_nqeqmBfyGNYL$k`yU$e&rAHPVKHQTe> zL=8Uy?srlASu;g1k?I!7+^OMmpZZQ*FKCAa5>B10YRH@eM4x)@2w1f&i?q2|vqi2? z%=v)u;>iSnx%C9i3?ZVTV9?i0_{XFtE9wema)AG4HJKZ_c}lk*s+1pBB^*Uy_igM1 zFu7)vHw!=4Gi?4Wv|=q;B$RdXAyH|CbYbRnmjn%e>7?zAf`$N&svSlvJb6__dD+SH z)Fv3ogK%KruOO~UJ(R@)6gTEdSeV4nC~?k0K{c1>MP>6hiQZF| z=`jjOHO07eOBu>-fVi-H}lKa);#}JxF6=j$n z2qohG%m8)V*u^;`>>(h(8DYsiPuz@*8ud-8aJ#=5E0<`lJz=n>?D$heHx$2->J9k-QkR3!6iG~r+uupK?Lj{zQk zvc{@y4iP<{Ul{aMXiX(Isf(>_85C(O-!L%YSWU^vTQi<~fD#A89ob}TBchRmNE-I4 zK}*3|Ca#<5hFB-$F&Pj6`5T)Yti^%>up0LFwq8q+ z2}2f^5W3NtgVMofy_^<1(PRjWe5%3v=&6}#DpV<(kp}y3VvC89OKJ>`uW5_*Q8*YW z4K}CN4+AZ>$CQCO+k^UsMDdYeH- z(7}|r>3`u(Gd4Kx0D%3~U+)LZzfghv)j4-P&tA}eSnIk1JE~f^^r{}?*H? z?@-^^6L#q<`r-4EHy)KT1%M3$kvYx?Px0@Mg>Iib31qEIRC z(9Zki_h?NlL4N?L?pA!fqoKM}9&5sY?DqAXsP0mAYW{NxzhJ0t>HL|I+OWF*KA=RG zo3Q~aejJez3--@$_t(I*I@EVoBDfYJJ?aM)R1e@H{3s?na+MY#J?f{a-`_~NR;=Rf zg{f#{kFe$MAX2_{e7!;(&p|*E z*3O@`pum~>F}^v*kmHT|qPP}7WW91oax4w(i4jst3Smhx5k-3lm?AGkupr+pXXu`H zZ+UhI7cXE8Psye^WNP7eTb}Q&c(J87pb)GWs;xkYJ&#r0%mRWiu>cQ38fm>s|JgGT z65GxM`BrEdW5$5+{c`qnBIN5qw0CpUg6)&bUBXLkRZl3bP}7FMVg~7XiVSk9vp0{8=hlar5haR<4f|)?W}^maT}L8+`%wN&%eH zs1Wx`A1|)(l%Nt`E1%E2>pWLOG zVw$WO+1uZ+nZT3$U?*gPjO92rYfzL)AmubLCW)SypFcp1(V!9#ojM$>cG$=ZLK8U9D4G+uA z!@6h^p7pqYX?Y8AYf>8kG>#r%K~^kpZ(Sp3Ta7Z^EIMj+|N7k{&=5*Y9&9>>We|Ip z_P{0698)p~#pLdl7i_)*tTdp<6ZWU-OJv^di^0W072glJR0~sPu*Tm)S#vFA*%EzT z8o`?WSs`WUDXi&Y-FnwZWf-frIyc3yYm_#+#A4yZ~K0Z-?e0KKXE0s*6<}eLKY?^{AZPKt!c*m+o zWm)fq3)V=pZMTuNV4}(eU}{wne*{Y(e(*ham5(CPAm-k|2BE;uL8tWa%lU7BpDj;! z<@7cFa=I(HQFFo1vJ+v99lVcRF5WMLwoxOoR3qL%xg;J8JrO}jT-JSNc#4|H@&{8V zTdy2;_xOYU^|;ZU1ku3nTOGTNJAdnmmQ%t4Ts`FA!>w7;WN*r(3i7_dJxqYp5TelI zTuiYOS_7%zYD$%OXyO32OiQWq%Zc`iN~$77R0TcTwU3LlCqn{A+lb(FBTjRre46Un z>uo$j-zRueSjowS>@qmj5)ReY21mg@W-Me_dh6X=7Ef|m1KsJ(t@^7*&N>!;Y}thB zGwaKmGHAnC6uY{ohfTdM^y4v0OGw*xX;@L`<^(7wnK5qjAQ&b*$`?jX;OnZPZ1 z5}>ca+06Y?`!!F2!4o-Rq@++?n>H7hUeu`mrI2!uH|$olbN|_b(Yl#ih5NURFVBRn zP(@i$FK`Pgl2Gj#ZwBoA)l1f9oRT89FqSY@996>|DgRU=52izbXxxfljl3(ma7u9Q zrECKA%%oeRG;M%@=>v@48MIWxR*9E|&WenCLe@~}e9+c{qN&c^fNpyQED);g2(nM@ zQ%Wza$XCf`#4wp1@(=bzFduqN4rl>T*aHl_{j~dNfvXw0X*iR&8toEIZ)9l@pAc-t zd>TGKj?^PxAF}<5Zs$q4jLO6D;53U4lV`S>h`Ky}%)L+PVwaWHvAF}1#BDGWm2N|ijTpA+7szp#1Mj~AbK}kn zHhEikgh3m_F`4g|objz5RDNPCyyFizs5Iui%G^iXD`^{DS^IF#Co)Kt1BoGFKP==$1He-0IVDi= zLy~C%!#aw+n{v7Umu@zEsAO{6m;|g`!W9E}x^WlYA(bF;s|7-3$J?9U-9RZlE2&F1 zmZKYMPxnYH-D8Ymd)b&6v4~eBP{P-+9sbP?3C1U1qrVTtm#A&hKY*%H=v%*#W5_zc zc!2#?y0Zg$Yqfdsz|FOBoo0%ybInZ6Ou{5Xva;P`W#-|5X}@HFS2uTzjZG6TIpW|q z@z6y#Ot*00aM`=I>W&oM)rO3}Juo8a!b8qHRobGDYJhigh9s-3aiX_Kao_b-T!a0> z9a9c2;*G^_+-i|gUQv!f!xqJ5yn^T0uAmq01=#J+RR_zH8ui-NW@l%&38VStfYBBZ zW=%|Ci+pBXKo9MC4>)Q2muZ$tB8;lCGKnY<^}OU`J%*6Q$Ur+AGg%dTbbtaMwUSmB zmOjYH#Mv4AY!9!Z-Z6Rw5?CO(p)h2%i=^dgZ@EC*)j_`jWHD5fmQIsXjAbQJs2q6Q zCC%6sZD>?1jz5b)t-K69xpi~1w?7$2fC6&`grl?CYK$zVGt$4kVN*B)q^xpbn6B5v zpE`I99Hh6Cl{(A}f?y_=#uWUiI>y`nwfT=pcwPc&E&I}`@&e7wvi(uxt`dk9_#lF< zb7K$2ThSEd9p@IPZ;A_!P?S%8C;-SB?fWLO17p>-LJz&EsILOJrEWr$wXJMt|Kh`4 z^5~}@r)y+%v6vrwETw!b&)D=79~dsx0aFVz#)H%9eB+pc5e1hR6%wi69HlEm5(9Liks3f%7Jgpu$@l%Vhb>nIJs`-H=ksUy6#p4Y-kMMUklGyXfd4 z#8;`}0=A62Ajce;a{jdXdqD2A^oZA^~8gR{oZDTC7hz8g+(A z<#Bs2;|&r?B~yrFGHyyXEP^w9UspRvfK|1a@u;U7{pLrNUB)Ficg_ZsWe}Qa7)-(ntXQpzX$9wANV92 zXeoYmh^1ezHo;r2K*+R89EAFd-}>({-Z#>T;$Psa2FR%RhdDqNQT>j0yzxt|z3 z2%(Qt0MsR9TPhGzWxYx@M668O&xI@g8D_Rvp z6>cJ}T-@W3__%8_&mihHcbtD9EWg?$vfjq3#qsy$QC5QH>iEp`OrRIE zKO|JZDHWNhPW`qEZmJIJdE6WDb0+c$E|HAyry=v}wnd+&m;37rrCTEgkU?PTa90v% z^4^ifP+x{z5Z+Fc>pyg5&1`s-ea4w6SoTwfK-(gAVdNON=-4-2XPJLKJ7|HUuD$>~ zU6?Xnkh*7^OUp{Z%$r>FR|%p?$9XwxT-^YV6++ACen5QzPP1kUC>`hs%~Q+nAVgw4Jfunsf>vk=q{NRIjer()zCz=+hd7 z?{UW5Phq`Ja)^fk9H+)yPcg*f`xG>(z+M)B8}0m$yYs~Kyl*tUZ{qMz*ZF&#bN^{| z(KtNC;lJMV`x`8u>SGU6=J9X!zNJiKrQKJf{QsQCc zXtdfQCJLCSYDd6g2QSMh-!qf9wc1;9o3uKtr8G5Vx0HKq^xQXVQxElU)zmX9N#^)b z$Wg=3Xp{f|NH|jfgAK2wfkU5nybpy!TBP6+={qxK1Ooue@$niE8*wFvZ^y(X2-lY> zV!s96v%Z9W${ifCAiS~vTz8>BePz9U=){2i$bLNc%$rX5WOfI@{o9lpTSnANF3xZy zcu8d-Xf)PX$u}R(#Q3I|p+=jq9wl0h>E0ml8w+rnDOsLm;tzKjBIr4xO%BCC?CFh4 z(kJRmSsW1vm~Y0<1=fD5btgnK#vPM)B=!A}gjq0UCSw>KRfGjGARXR2OP;v$?k6TX zs_8X~xyu_&`5WjYK4idhksB5SSX%Yu)ni^+)A|xC;F(Dhv_}+OCv$f^0$a8$6;Biw=#z&^NAuVa1WYYq47zk?AHPtNXiwnQd~u!j znQO6HG*QA2^-s1~O@sO!l=08e{rnmTU$n4Jf*+OmIy{K9hU8k;ta@75Zle_dz0w-TR;jHXY!$ge$!CMtrn=0EF@y8K)@wg zD#HGqx=q%-@oU;$^bxa-?X<>y8pjt>gH9HA3gkvCoYW*5tL5rEY)5(;T(vY`nq!TY z?u%&cF#VDUW7Xlt%IIn%?@jj3h!s@)yoE}e4r{_As-Dx^FL4!#D4C7UhWzJG`o#3b z7`>W4mY5c$xaVE8?s#zZXKt~U<>z0e2c>(eJz9dnb2=86WA;?RZ80QG?{fGsoGr9owTUrC#dm59mMn7?C&BWWj-;fN<5yD zMz56%YpXrKb1sf=-0O%tH&K_W^G*?h2Fv#Gr+c*goudgB5+Bj77Sn-LtU5?8 zl7m%EmqyL?kWcFf_1@&u_cXIows!i!kv2^ZrBOBa4q^TgNiF=n?h_bB7_>e^WELTZ z?hEp#;5b|8P*`&Y59sH52MVRoOR z0~w^K1~FHWZK8Cd#v_dDy?~|Gfr;17gd|)rV#$jXtJsbOFWLDVqGSeTlHY2H<&L-f2mlo@e=zisypIz zyvt(17Mi|lgtjiqNIA-P=e>|U++?4zbpX6qMoT?IiGOHeCieRZA~$!uW>2|(^aUSa zb0!+|dX=H>53!%4_&*#W(r0fSLWI&Qe@1@WZ-xrUQSDKuAR6u9fqZza<07>iDmoDp z4-IiQoLX}#2GzMxB>K*L&Y$b2r=b^Huhq||dvy{PPIv@CgL{!;$K9fRFY7m(TatXx zA)Eq=wn2(k3^Ha5J29T$&mJ*=aAzXD*=!P4_1<5k%t}Y*L%UoEtRL z0syL+aK2Gf0~8=XwHY!$9mRGKShJ(PGw1P=>2L@J8Vw)DtA&butNSxV%AuhsZ{ z{kf3h(sZ5GVl&QHrfiT>woo($kctIO4S6c0Xb%z4ZLSYsgL5p5U*LXWk>-kL;48tOY+_d z3I$LoK_U5gL(K$O)NS%v9Z@sucR|eL!Eobv8woqXxCvwU5D7*pRSGhBDuVmEVO0ao zg|&i1(>j{SuxwZT$dE~u0t)gf#fVg~gTr(9R?ktD%Vm?cGY^9Ni`Hbu%gC0ti}0!o zah_)x#m$3Yf<57s0_Hwd%kxJn`mJL}%ydWy;|U?{+KZ{JKQQBq=4VQl z+cS$6NKP;?IaSiUaM-3&a}=+Pn!?`^s=*~A`OE$dQX0f5 zJ4wtf%%BpSvX_H(xXy*x(xG~G{TUmn313msTnVO>*v>CN_{@K~--(_`w;p!o!}oPD zLjCLyJ(1PTFlQC@*}b^~G`!QWVgmvh$j}~YSr^4zzvP~lu!o9n^i1C5#CAu=IUkp& zkG;jL#hdvqHT)g?U*B#nUeEX4$=;I$N&nl^&D*cXl3aXS?RFOrr;nK`@--DDr^7;O zq*AhCsX%-Z=(1daNvQ&dRZnQw2_GU3<7q$ZkU0JFzH9Y%2JCB~#t+@CtRMcLN0$Bq zH3B(=AB_nh(zgY^XY)z+w)aCA{@r0%Qk0-`7wDW1@=IXNe{4$Ju5F`kn-W-u*OYsE zY$ku#PE0zxVNlOPg{S{XaS9+jj=7oQbKiNqe{p_?#C^Q3H}#;;zW&sIevM4!pnG|7 zcX|1(t$)6+Po4VRxvDk*EOOkF=e~wXqL6wVNAB>?%_`YlmeJOsKMTsNzm`sntkAz5 zP5j4Pv@1I}RW-c1x$brHE!92k^>}hOq2&Gv1^~#C$d}|OVZnv*DL^%nmHLVu1Zh{- zbI95t5Y%UB{e!959#y(C*Y_x(d0)!-hdQo!&L{y?;qFp&=$>Hs5p9$$vHF{hmUC)}8{#nmbe57G8b8{d4Aif4(cJh!%rE z<(&l!fR#{`O611VH!PDF<#pB|8Tj7{u;6lEHpm@agnf5g5<@`9u+e0F{sU#ulGmWYo1)sEmxRUc$R4c2}{jrD4u2}h%kdeXK^RRxf$d$#E@5t(7}l# z+pOD)-P<9WhCf@H=6gIi!4o=}DBn%9lP7(>bL-UQ)bMOoIBZk1sEeiNm1a)gCDTOo<6dx6rDRaUnNWkSX_b2P-1 zW)@ZnOIz854643(V@E2T`1Ml9D5HxSTO@!8e_l1|z=OnEVY2!}#X|E1v6|LqwC;d5 zrDoXNUQSM9FkB(75+aK1MZS1rf@uLn$b$`SJ`1bHus7T`m3QJ1TJK5B_-fMH;=W^7 z*3d940Gj$|8K}Gta2A8&>xv!<8@R&xV`DBNIO4SsLn2VmXq#)V{bPtdl?oifwPu|D#f=D6$}`?T$F8M?U@#lAt>eU}(Tua4v|U$kOiNaAai z6hz>S>(!*bck6h5@S3(V07(@7$j)ltC}c}XgioQ(F34%}HBVcU0sfrXiR}h-hOw)D z$c~}@gSHdY+qD$na)~wiZTI>(=oX?Y>V1@MNQ=Yz2*Tw!rBEm|@J35Iiq-%54 z`i@o18o!U-k4&s@1!DUWoO@J+w~ONf&xhm254gRb+A&lVS2k7` z2Ol7@SE0j{0rtz%N!ZjrBvsmB3iAqpZfw7&^Yh`4IXK4{$;z*T(JG%4OfB1IZw^b! zmL+qJpO{~$%$%eCqZBF_51Q4z%oep68#NantH-0T$W5KSoxv`m=BU5A73dIJ?;Hvi z&Ad_CG+HhFj`kFrT&D2XSVpV+&BkozZ^!MZenyHHq`>5c&YL~r%PLY)bb+b>S=CQx zsC&sYqi_W?&`eXRTPXBIeB`yCOEs7G>B)sBjA(;Ws2-$1b0+w;;#$0P?$XKL|JyUsrfj21&T|cROa)L#weuxB=lFV z@FtQt=zTEaP3l_0BaNN>>wX^mM|?FAH|2I16gG>hbQT7}8dCw&#hJy9ol|RkxVhTx zlk6wWL(c9TfA%8BlUU!TAkoUg$*HN{Y2@7~fjAy(XKU#!x>{{wk}fwzMrhJK38^Bw zINi&Lkk8Qh7s&d;L}R#Z{mr6RL1WR}ks|$xa8{HEQNl7e+QC16(tVde;gd=-IO#g^ zx#VagGqn~bBQLeAJumgl$S_^E#NNnvvAziga_4=+EAoyjm!cl{?ES+2k*S~Hzx`;*nvRIW?tv9uC zHF9U?e`D`l2n)u^baS+gNy&IB#47Sp19wUO&1x`op8l+e6_)3$o=?!2Iz;_5C(hL0 zWNH7Fz*nh;CE?sBy+)whNQH`Ozx;U)Tc{Z# z56wCo&`xc8AX*fcL$n_e)cOUpn}3n2dxCWR$}wH3O;(fubZzb%DT$Q%Mn3?{=AFKh zurHgB&gi=4)RO&^wZ>;RHxKD#0T)C7eIarIu}bpFl|Eu&$_JKV-T7uVx5`|R$U!j) ze0k#K#|eD#I>7p}ci5cQ9A~oR0p{%;1H8Qp%ndek_vQIc05h`Zf1^-6w*-c=F7Nsj zrI~HTI$CbTho=JT46?7h1V0W0n3-AbPcOY*h(MF4lkbtuAwt#} z_WD6DXXtsHS-rhw=J(okp#RNQ1#$jAY*n!v2IZYd?f2|D08x@qa-X(s+3fqZ3Ji4T zD~E7}aaw>}`oXF5U>@stru!1x%E3=E9{BXLS+oQlceP7xkwrvGkc|UR*cdd|DN25A45;w$_aZK0PEzulRRE_-C&;7R{J3K_BiDy@C?Z#$coqx9>oL zn?0IuaXCEmo}9s2X)rbLD=_6Nhg!7of1sB4ufSA*xu{hs7Qlr3KvY=Jd%sU-^K2+c zWkb;Co|yYm{@Rv7V{E?_E{TjuwkRoU7|vk__H29-;Rt1UTeC>XKBQ6p*^^z_5x6x?(?fePUHbw@ebidXXkJP@ zUAD8YB5?oA;Cm_RX-TAoWD9)DMnnt_sgIGu`U_2UorJA1+pdO%9%O9w%6NK_t<*;x zLGyIIIC6d$r(;m>l2CJ%oaYD%_;Ikfhp;xG*7})KFj-iL)@eF6H9mICWiewbNfgXG z661<_(_5_H4K0A%Y*QQ9>r9~j#`NzaG~~5eGvZB&cvQC8*4((7KKqkG#6KZ#8;VAS zcohM}n=w_6<_KoN^j-7-#F7H>cNjbSSF%~pm*E7=m<*)Dic(4zJ+#;{fhh0SI)<}# z#nBzNDHIj#g^6eq<)kkCWu7vRa5{m!Rtjf(I2j`OqG26acc_o(7^8=(rh3`2>dpkJ zsqP+O39E(>s#(y5oJ(*?%r1~tKg*74^#9|#WyH!-bHB%6H+Rr#O0?R1ZKib6-e7AL zC5I0!GL)1ZCSZ;!PZK$`=w_1&*IA}8^5_94HC``VYfMgeUR{+`h;d2X|wl#m;_AHE%xB+Ve3(5_OYdJip>h?(D>+g z>dZLLH>ho~Z%K!1BNL5(Li#}CbQ)l zK14R6X8pKxs|Gl+>KH}XvG!!JWQ1XIB}%;Gde4AfccA_vq3SFJ#d^ZzOw%n7a!n&w z(&RZL?*b@pfszwClR|e#!-y$_i-eb_0gy|;-R{2L_+!g8GJy;1-W4ajGep)X`Lz268iE3syc@Ly+Q z6&e{XjP@EXXh!mx4IR>dYR(?YLIrLCj#P|P$D*mkt(ql}#1K`!!o7hWrVV3VVoOe$ z!MR}jM3GEYuUBA*W-=@zl#3Vv&IQ7r8xL1V*xO{3JN!d-iFr&_O1J5k1#0qQ^A3Om zJez-qKSyr5F!_4D`)9FaPC$?yxO-t_&iJgT?*Mi79#Ctu7IG8*m|0l01I6`u>4|n> zb-$Gi8=)xDh}m^8rslca>-{|FHwnO9a~TNZGJVR4iehn>mNWZj}S8YT-3N`JYm`0m@LqI!yE zqtmSDXpDXF> zQ8#=Ak!)$+N|1@0QaTHl_4zJWZk$rmY#px@*d&u%83=IukAR`&^0%5t)BK;vWz zFY&X=Li&T$MB9a0VJb7dTK28l%XMmTAK=@4U=iot#<4sbko$icfR8ciUiZke`m5LIjbWXA9%uL8_ zr}eGLTjVMA6rh+l4fh=lQLid5SbA$n%W7{|cB}hPzrm;rD892OZ!z=S5$zRXB70Pr zQUCm?o)Yr5?kj3LN4=|iqT5P^uT9MI%vc*1B|p)uGuag=xm>URw`OOU>-zrQfbBfD#b~rs`eS|6PRIL?iUI zbDa$u-bL*@Y~>1erCeB7Wel$8uSqA2{Kc8}s+a38w)$A~Cc|n7?X11BJ>|P&@0OIf z!PLNQxbcU}M}dhJ3PP&NC5YL)Ut6l`Ha%pf)Dc~oCz81?Jjy79vJN6DKN|fD_1c^x zRkRgjMtb1v=RVY3$0UkR5IlNSX%-Iv`~)c!5`-QVj3XPBhv<^M9Iko5b=XYmQt8{B zvXd*Moy(Q#z|!EpfM&*(Xz8D8N7`PmG@U9=3O8M;%yk9%-K)`tw%vTPkS<`mOogTYC(U$eodp>r{}33#xR>Q{(c%%fN{yE=#umd2t&RMA#!1)2+#2)@}hite3Km}Ie%rOUxg#u z?2Y%y{0WW^r>&dg;U_}Z90FCt)veb$TKEpXp5ejLbT#{KBYcYv3DA(52le213_h%W zXYmmY_9Bq<6=q2;at)yd-*pN!NG7k*x(h6UAY(s0*f@0e*n7V&kfR$%0mNr|ACj6k zH~1|HQT1d^B7!eNo(n^w!umc<%s(ms1B@>c*u}AE&uRhJXojQ{PAmuZ8qmsDIBsW* zEu1x7Cuvp?bfOAzk5=x>iNZSt5@k_=KON=R@+(dDN#Zg>qV(qS>)VX2;n)so$4KrVEa&GjEDC=eF>;iTOx->i@->3X8)c z?jHP3p4kCgIWV>yM9P-YNr{@3qB!~^9RJ~3nA z!nW4tJcSS3k|TXOPpfDp)QMJ7d6#f1PmYOYkql959X&_;<>qsFlkApm^Dw$f+l*;* z@7p%sk0d=E1gtL}ARKE#k)*xryW>y#`00CK=baHmMyVXQn3*DJ$~xd~4q`NblzO%J zK>=D6_DB7pB8-8)TD8}G&D|xgbV}9&A-rO#R{%~M9-rmd!qJ5smhjF?trNF`w1qha zakakSa_@#M^9k{%%)N>Wjc`r_egS7oy_SYJY#A21Ug}Oh6ommIpaugdx1mDO*bT2t z(Ng>l1Psm^_rL^-I7wO=8gpU~hSWz=MIVAJY<^U@#(CkPekg!*EFEb$@Od9`x!=Vin<%d!X}hVy^E-S9%lGi+ zr<*i=^X$+Nf2%uwp0$w)fGJck+7)^$Ui}cmVGX`>U<6dia;yr9y;T^psdOY_e4%@* z87{J_>S4s&IJ@!fvFhm9<@wl?GnX~nz>O%}EKNlw8rscj7f zu-;Bec(re0+4;%R3a6WH%&J%_c5Y4UE(;l^CIM%%;3(BVS$45aPOKHAC~@wBiZOav zLeP^9>x8;%lbdQ*nXt(!!p)iyzL6Qm+RPJ~k}EQerisg{?WT#YWR$&#WYE6yvCqvF zvCiPY;heM{Q$~Ck0!Kf%u@PPVzbrdJPGGuL{C=dqGsJvmx)soxn^d;>lWjr06PIIs zO*I>@seNeL{t~T^fPEFpLFKF!kW+c)m`sZ$86%zlyuPwA77}939wuaWkx8k}cxL0r z17ZEt1vD)+Q}wLg(mn$Aq&A|s&M5Lf$FtiayKhc};hhww!{*~w{?Vhn3bVor z^I!D~RWCA-#7ew7t0M3AWZM>$i) z7*jgn5-6@KOn9ySCeMeWX(Y=H68$FVqILB>egEdeOUTi9TgVX72l}%W(F;Pv!CTff zx88DW!=zxV14eAl6+xy|{qOqTnPF{b`}_S}2@6wsP@{bh zNXvDE7{nLvQxZdOtKkFS5@17FbQ=2i!i0X^txUG<@ znxPJf0Q(|-O_64A=TU||&!mw3evCz)E!tj$3H~owGT=NZ-X*r87ngmMT9IZcY@icU zOqU27_s-7WSQh^wbLXL20LdFZ28hmUH@+SMN&6jEtGL-L$7Snc43Dy^7O7cv{hSvq zwEBIPkKH?Yt07jM^fL;B^8ZEGId)eTwOu;4ZL?xm#i$cIso1t{yJFk6Z5tKaws|^F zzm3tOyMMr5ANJU5?KS2-uQ{#Rw~<6!5&lOU#cFKIg>E~1{95IlX43l^^0Q(~hEI$i zEm)g)z<2lrc*AczSr&iZaS7EB`iaH;;w_Sr1zPJ~@?lmXer(~+B76B#G=#n?b@6dIC zizFlR19S96Zog=hE%x#v#ptOy8DJ-rcyIiTrd~^PME?-`C$@s=_;!tuhkAYK#cHZe zxa?RrEpJ614kwiD$eg9U2i}52SWSql_D69SZ_JzP4QEE;6VWhx+j;#tREY4tE<K*41JF5XlchYOw^xGev?6%3VXZw)6>G$7WvWYOPx_Lp=7&Y(L3Z~MaT^dVP!fda} z{OU&bmNgyrzDlamAhVbT8&2b?BO>L1V>sA9a3*v*(myv@9chKyAatsp^0OjfR4BWb zV()2Rm9AOE4=ho|sUU*=?CXp(kOtiZF%2S6V+?YT; zip?<7yQ+G1H_eLq2%lN299if(YY!iBfcm|kL9*oL~v>Fwt#oi!mfZH#M*FcpNerpH~3jd zyO!RAr5x?M4M(n?X1-1E{O9czQkd`?XeEO{_3T4!kUm0MN5w@VCs z{qPJOyVIq5A2O#-Gqd(cE(^U>|4b(P84>7O^jR6^vX`9{U!>N?R{~P;XND`IJX?8u zrQTX2msMpqAX!OOBNATi=#tJj`cE~u8M=041!$T)RSCoBl_hPQQntrPIK7`k73#t! zO&h;gJ)sG;r@?L7pu*9h+?a492(;8kOM0%>56I;U;o^Ff_S~^yt=5C?G~bg@b$5o> zw9M;JW3SccNdm!b?9MOp@o-1NjjGdjRY_rnt#DfBPAK4-+7wj;1k=Q3ffb~w_`j}f zOJ!Wqa{AoSsm^4OZ(_Uu2>F0QN?9u|%7~uRu%hf|yu%VW%V?f&sJ(!CIK|}M6!?Yg zJ_TO&CgbGMX@0S5$`OWXU`zF;actN>*%-su6|DoEbqp5&9(k2WfpT^|zWqJ#==Dpx z;zN3A?~n<~a(a4;!mP=vyy7I4%-9C|x6kZsa~3I|05}Y}!lLovgl}i1NK6CG+&q9A z!CvyM4RPxtM4W>fU|(;fMb}cJAA9KP{=dk7+HV)@v_)Gzr0&o z6WmzaimWjzhaVoyk6V=onFk*FfPif`TWC(ZxhjE|kGQP@FS9?FTVnq$<4;ie_)vpb zLzdYjwnj^5M;6IYCeQ4?03j0dRcp^+-mj#BEM zL=)8%?+dMfizYBEgAzesWw6bV{=+)s9pO|jKQ2xntk#221aDe@(heF~1N!XOuje5yq5a7bZ-(W`(l6V;d z3C?goH>t-gE+A1@FoSNZpDtlLlUn+^BMs_RDy7GR$cX zB^7u3(X1y|5vkdXgj?4|WpiHG;mvi}twSmF>|w|G(oBl3dsu(RxlRYzw!cxW|E2qF z#Fph57gt~G0tm58dYY)VvUpBy+T2w{`2L9~4}s5BioebxK845!1>3uu%t~9il^hQG zAi%V^Iagp5Cn*ePf&}pt2~V>8$cIXW>1quAKJp}X{jkBLoh%S7%j)^B&ugUV?q9K<~OqU zrE0|Gs?sbW!-P2R1CYQ`{nFLTO`)H@DUaCyP#&c@aRSvm2gi%^QIUU855FmoL2KwG zlmMrCMBM*S9^Bx)Dz!8UZcc}C?}AvMXtjoLYeLGymCa(0-Km&q3#>~ZCa6$uK8&ya+%Ip^mytkJqpT5zh(cEOb{ zuS!wV5S;4IBo|a1NF&ZDg!~y~vFt8+HVQN}dSvU(b1IB)4o|>+zz!vxovg-A1rRoz zbRPc1DUFemDa37@LDg%p##yQKiT8@kS}xqvc;}yyEdR~o_?gWvIeIQi!17IZI5fxp zhwe!8q@hn$l;zF`SR=6wD0BBV?;Qq#C_G*Az}G=uZxQ@m124Y`c6!wAbP?FNGDEM#F!K4= zK7~XnsVq@xdx>R(e_K+6-DfG5euvl}66Ek#nBFKnITN&k`v8Iekw|*-p6FH_N*_b@ zeUbg7SieZ!VtHwHq#B-+x?YTAD|U&Yd+3SX)pIpRxat?BjkRKz%2UEGn4`wBGVJlr z3HbdL2R9+;+1BFS(gLK>Qs(R+E;XFt9$hjoY`4ZId!0zu9Lqi|q`ImId@)R5QMs2WTy9oK34 z!QQ_4LvRdA1(8aP%QLBCwPFcTcWqO-esv0&BxkrG&homb>AC#hkzNkc?l)=yC3Rj~ zzU_9@KRGy`8~UM)K{hHX;sTM0reNtAi2JbiFi6!`eDzz{t>lC_AHQTv&{G$7>)8O8ibsncn(X7H)(YVvgYP;rDVz_)7!{dP2r|ZAV4B!jrQ`xfu zoRYuh#b$o@8uD;1^@7Y_`b3O6xp*r`WNUSb6Pd;|0r&BJ-3LCW&wRwqi`s z-NAF*k6~E+HtKJW3CJt%xPCn`;Mb-Q#d?F&s~F;W*F9FRctjDGK&I(%SB)+)O5w!b z?sJmun{tZOt2A`7;0kyoVjrsJ`RT>iY@E4o=oYj!;nb3_fDj(tz4)N+|5NWr5%&#a zv74`QN!5lWk=yIbqvtG48Vtri6%_nMO+poi*`jY44UA%?wWqc&${%F~Koqb|EHMb< zl}<*})foh~uEEmz938A+*;toMb24@~Bqujuap-n%byI~3MuZHQ{o_N12Jg+N-aZE` zphC%lG4H4qcHIZXPeRbxXNJVMkAbT&Z+#X2`P?#V2y2nK1c<$FqDk^e!I}3QXL31R z<{5l{FdMssqwrvp%t+((k?gnh_yCa#Ar^NK{h#Tzsn;vx2##;3)N@5syn!~3|Ln$( z^VHdwq`?fTj=_B@C|zYDO=ExcQHJ(rTgs* z8$|3Dy987p07o~iH$l|)W4OndWPmtKe(Mhi02c+wLg%(ZWg3d06F-k5lb0g|@RRq@ z_(fl8$qA1W)|4C zi%w8Ir3@wCKp7;zj$)kax5&$yz%w)nwQA5$XBs-_U)KH;y_pbB(j#OEfp!x|GyQXb z!eWa&F{5Ro(5|Z~8_jRVfIRw}F>uQBD&`vNu8(ug!`9st;gvJ5{$>m=!FZx;NB_W| zS36{}iwFk$NkU?$S%(BSX;}=RjQ$OgQ=2xGnx%q!@3V@0eT^91YRN1FV5yex@y3(w zgrb&*cbF83vP{xRG#EXxy#3I&FAC0!R+D;P!xB2(*a(+|J^pm&tDLN)U8z4|+q`|% zdB@~<*WuM_fUt^|Hp^I(`ei!}UHDSN96Hy6_^?Kc-QdZiiS>1|I{fT(c&24}o^B~K z0!KTiF_d{xbQ1ttk`}iak!hI}tu35N&$XNR5*M29QQ!Z1b4*GVZ@9((91-mB1g_a# z_aAIPB};GPgmEG|HgM7kmSJ_Uycj!WqJdB{PA&YTndIrsGWK6*(@_<2e9MoQTIOMk zJ{W9O4%B*+G68m}MM2tNat`csJl3`PaK7bG?2gzRhFdV4It+GoW$RyDZb~!hG?-cl z1;gwb=C0?-pcI%-6$zG-qlw7F37Z4c z$WF3ptLF!(aCL9VLkOZ6!&C*d>rg(j?l-%wheN25iZRmxiDvpgWv?KH%q$a25{>K4 z?<}|SWPNF@MKh&mG;t9P^vE7{!eLH%{vK0me;->euW_(mOn_({9W!NEOVgk*pTl7C zY6G?L5F;T1S|#sxGxH?}emeU(g??h`A&Efxln@;{i!l+owq4h5J$$d73HGq0U!QCj zn-?!L(YvR88$V>BEuDa%vzrJit3HVLZ|rx}t`9S$CLJ;vy)nY1(x;%;65DV3ib_#! z(kD>btuTQ?#LeSkEt_7?e!<2jdu)8)wN}0PZM}Lzg9{YspMIc%Rg**33yxd z%U$4}zztFmgxDn^SU5#bu)aFFon6OytT?-Eb_p99wl=X&pWKjZ{6QARa*LY6y)NFK z9Kn}{uHVDIE3ELvRGD2DulP97YS7V`qBp;4d0h}o1&LCIr4`KfHBm!-Xhv%(08J6a z<$6h@t4}iS5ySx?PLs)gg0v5t0e{&AhptgzR;?z5L1xczhhpHRo^v6q2=KJ8el@Y! zvn)YIat(W@V_q~)RYJxp)&;rs0B!)$ z$Z9Teo?v&L_vd2gPpVzYg*3Qj|w2Ibbh2v6vngNkIxJ)KLm_n$$QN<)N0>h9< zU#KPSOVF$xN+nL6B6Lkwqu}Li^(|(6V%bmpp!S7$(9Po-&B@qCqtdgch+`2}PavA_ zaZBHtp{ePez1HH^91_JOFMyBojw3kQk2K5;&SAr{esGV6@<(NumyEAjLH$b|Jw^2> zF+(slQi5J;`5&7?HDP&^$iCtF@`m7vsbWo(A6(zjD>Nw#VhXid1sHU3P?L-M&d>2R zOI<{`yf8 z8*oouY50$#y&#l44HR_+OBu0#11DDKDZ?AEXI$ozS{MjJxptCL!pmqF@<1XDibsW~=M%=IdqC{Q2SJGL#FtM2t*gxWsj& zhtQk%*IBm*@M-5IOF^Nt<>2SU)IF7o%(xglpCTTg*x&fFt%KY*w6E-UL9fAFiWETMeLH( zU~6mYdX3EE$>fsV^%B_95CNGQ@FZ~CDIlFsGe)QS@a6B5&HLEwvv%j9KwKE% zZJVxT^%)?y^QzC@oe`9x8s5^<@I3jRv=aS%G_{*ha`S{J2v&;XO_dm%?8yA&UmniI z5OXj2|91Je-h8|K3nG;#4Cg=<v>d|o54Zt`55Y3J`1dW&;cr!06lM- zih&g`{~mgZfgGPedx66fU}a*CcliP^D@XTBYXSJj%i>LU0hs;;Y|RmV6Cge1hOdlLA(cgR>CQF3A_CtnMYuPqYnONQbhGW)k&$`!y$9LUNGBX)shwNc&F z=ln?z1soH|^&Gh13n{7v0lGfBt&Uf1yuW(l<*dIdrhF%ufzFT|Cwq^R!?O5a z%e|V2+ub%Y0YW0dQ_O8t}aFa;ty^lT^l}=B!P;UXaJ^ z^=>KgCSy^|PgpAGg@YgcEAXGLLJs&c)%!&XLR+9G*c0buXH0U+AYKHO5kc#38hDM~ zsX<&MvxG>+FsKun0!vdraIQvjL&=sl(Rc*u6z@Fke88NOX*siBxccr+)7K{ENiHD* z^`xPNBt=rhtYuq;Oxy`6=G^`q^e!#WbDl1=_WXEc9Lg!WR9pi;=7+{u18c7lb~dL@RMyb{VNjuYr)#D-g&j3$ka?~hA zPD1?N*^=9P;Yvo+bh*)sRGAjnnYsB9{;NtA7gRc$5RC71&Y6sJRNghCNS zmn%cnL!N&}@M5f^SQrW&*zo@(2rUk?Ic!zjGncY;sy*vzAm22^-UHdmQoCZ#zIvE) z1S+n9l?M$gpVSHyegS9i!25};&Hrp`bK8~{;JFNYJH*_rhlDrAyKj%Op1!H;^WpTp zfSYYHJJI2N;5Cr-Mwe$ThtE#%Q~k{p^Idlb*wXN>_zc{7e?49U+EV7M0c)Osn(08@ z7EczL;)L9FOinIei1n#6dnQH_+(d);9AQ}&Y`Gh(rL?6uAivNdYVOV$x=ysBd_K=F z#Y}IeP69yfNE)IscN0fw@vx~2H)DevbSdMX4`)mK`fk8s}q9jp(kYEbQWJG^cdt^P@jFD z1B5&htA-=}_cAm21espNf7~uf5p{z1m4vyF5RO&-;ZFwwi-F_q-8MYs@}9aA7JSsDj+m4R`bEb1?Zry5~tPDaLO5pSScnAR=PN~~_4f76=kU!E>@$4*D~U3*Lfr;^(m=u9CcpJD7$0pLWLByt$=XuLs{f{J7Rl~?ok zAI3WXE~jQ8Y|JrD!m!@jn$t}E#L*HD+&Rs^p{*!qeCeJB6{vs!O2KIo2eM?}JXA41 zJ)ImJ>@1UGhwPe;f|ME>(jfFV9cB{RJ~{0qcR2O4VM+!|N?-Y{(w@i)((YV_cw6WV2 z`?bjqnyfT(f)J^GnK&XICP>i`nV-I#Xw=$_vb9#T6KVWh3boB_?-dn!%Tn zEOz=(L#deV^)mS?xv`)=N&AN?R6`&^Kd@k&y77$hb229(a*Lnqv}(S5qYbovV!Zs1CXG#hW+Kj!`GT~(_Lv~a#6)6sp0zG2^TbuQi(ZR3e zrqj&pAMI?SmDe$7Ww`|k3{@%Y_#0X-(II=|X{IQ#xxPiZE8rkEIAzEC8sWFX$%m+n zAZ z65;IW2TmEe(j}a@HA|CQ4=KPmec42UFP4}-|7`NRH-L9kRqW-da zBvn6!V^Ay5K<=G$rTHcWls0&@0?xM3vrq4jhbzLz7S$EqQT2l=-;!qgyVDyKjG^V6 zEw?Gt;Hg-8j2*XMFj~^k;8jD*&?B~Xi`gl-|7h-@YCn5Bg6BZ6^NFASmbbG0E9-;< zQ!}F)9(L}`dZ=3Y9%*Foqn|I|KGmz#Kc2YF%#U~}5?;Te!*a(tb@<;WqFZO?rfRFx z@P3Yj;`-m*?4wo&5<(%f=BK9b7ov^3WX);%9X^f!?NpZL$nPP%}XCk4wNt04-xM4)eeOa0dZdhhWpHsmI8KRXkE z_rs+G(SFsr1`EHh1Pxv=%`|T?MX~FDQhN}-hRhWcq9g7kp~elAM1>M88L=POkr$8z zf(`aMjU>ukx-rdjomD$^rl{)<*SmD);4-4MteDbMZ(}(>TrI43IwBlM5L$>ee|H8S z@GHdNzO632^_eIKl7d%4X3_o-Ub(R5=bDU={YLu!D|c)4Ic;1$gn&sCN$v7!CUefS_8lpv2`wXIc(V?FDcj8FhSMth zsE>OcJGzQG#S@-^aB;0 zL`O_l9nGE`G0nZ{*<#ZXflZ}-f5!u=`@z<)96148@23TAg6 z!ud^lC)63gF0N*%=hFNcbE@EVfQ{K}ICd zv0axHD#!D=u4)9L{;mBsmkPk12o>aSGwDdatYu3 zP-p5yN~jXr0k5MB{NB11aG~r;NHmC-jjq6dTcpDhce5zUdcx?1??&B5GPj1_C>m5L z%=a4M*v(*=p$*%zO(5l~+bGzP`Tt3~n za`UU~Pu5JkP25tdEEK%+ADct90C(r-Z}SXzZb-qf>$&5)(*3HdGvXEi7Az(Qru1nB zRYi#&)SNqT4cV1AI@nr6`zB2HH#m;!6EusUm6v2xF*$G#Y?PUZnWm~!Yz8VZrZon( zO>xivuajwNcrgotDGE%RFZoigwkR&*W!)Vv&69TvP-q|Lx;gRNLZ; z2(S^E(J|CGf+Xo$g~nGBjkCZmQ7Jqu-bLv3YcA2g zORV=gfYD-fwLwzRo#)kEBtWhET$w-)`!M9>t2;;;%S0)xcH{u&6nRhF|6YQb=!K6F zhpKmtZ3ik1uqh3Ovx|_9wH^lRb+Jzdl|N0{ddLZ`e^b~!_+tJAasWchtc6ryF#n1$ zI#|uGN|}3lOR<7xS;fva)X|leSv)HfU{5Lu@=d+ZLC9r6GAZG$Spzq=ytnFYknBbE z{x~Hwpj7|RJo=fEAFuS$f!T+TA+g_Qr&c#RsJ&WV?bq@3fS!N;B`3hLR19aX#Sf@= zXH?VC)$Ckt)0(!xiW{$+fl}i^~Kgd!xLY1zKDwB)}ao)Et zzhYY$=!=0-<1~Hwgyt#J$_AV|BfK$4?0#xoPkQo$%++XFl>>V&GIDv)cD3d4-z2!& z@{NHZA)`gCo%YegUCBZ8506>ke`Hg4#^K^VORhf?mtM+-AQutH=?nCJlDP;Ep?It* z*7dT~CJdBiiK?TjAvWu9w40F>d+X-jch_nIEOUA^bYlIa}vtiuWSRPm344JLDo@ z*q?A#p`GdX+LaFK*%EO?S9?QijP|s0(4~mskmYJE^;ZlC(lOTw7q*op55ZKIb~f*q zC7NnVb94-I8_o>`J+Nu}ji{jEQnSb@mC52R5Z9}(Ywpq%_lBmN3WUI`oFG?;1GF0A zvPPWf&`V4H)$Sk8FSX~8P8CAYj&j=jEz^(&c2>iIV0oJ%0DG%fo3HFhUY>+zWyOJA zz@au`l*+L}y+}RIC`SWmtY<=Y1k&ie5= z(yaHq{#lAWP=mTf9@gT{M?!BN&cFiI`DkN~@_ar_9OUiOt4MTXa0U4*O-xY=Km5{c zXc--OMUR^_D;L%t@mU>pm4G=vJQ%5ODq`W##3yENQ^((}%>Gqyk$Bt1dnAl}+qLse_niKCX=dxh?jVjtew)p0dIF4Db4 zS$43+Xrd;1gQFL9Du|euwFkNk$V;N|xpQeaxNzM_k}?5l9u^3JjK25p@5OQtvHB2x zJLk@;J;9@}L!$U~2d1pT+`5!)$u@6n!m&*CO!@_+HgymMgq=8$M}Mn}=Q#UD@-+L#qO3uL_IW?;d4z1BdN`+c zq{JN8&7?Pv%pvIT9&NE+v0jAVm5dHM>QzKVtCrGQetllet3K`}0amB6TORL@Iz`E4 zf_Mn;pl0tS-JG(t$Rt=$szc>@@8ZJI(5+?hnW?4UXCHnIx;l{ONSah`T*Kb-oGgO- z_zQwA|0RLnsuAzQ9zLf5Jt)%Ow@lH;D(O#qZ#~`}&4C*!7vf6*W0F{BMN*v{>S>U=aQX{_zze1_1R4a1w99)JvWys*L=-kI z3kVqm3L>D!F<=(i7Xb7+mbj$pp)QA$F`I*=dc_BH`Ajl=iC0u65uRoNoj(t^8<*>uymUP5>%6luG6DMWuc4FS$gyFX8}Meui5`UL0cGO3o}3&v>_ zV{Q(3z-U;*%V1*qvjuQwQK6L)+4T{-v|^ETVTh?Wrqz!9HuVy7vc{`1_WPCqKjHT2 zs#N*wC3^Q|m1ZjG(o{kuu(K$RTKzK`pv7iCSQ>4PiBE$4z;neL7u3jy@MuvLa7A5C zFi<>3pJ-Kh1wOu2GRY0MfkRVfKL{Ca={kRUA2=E+pRFRX_X7%e%r&TwpRKf2FnaD9 zqU>ne7KlZWd5Aw!sCGsqv2P5sHLZ%bU+f%C)s|XiCkmII50;9iFlOUA@sjzhABHqaI2Dkot*uf6d94PG{MGCAe6!&E+?8f z+a|s{WIf$locS-cp~srdNSBaNu$fr#Eo*y8SewIA4=a(VypD?`(3EoFtB~|4q?WJ( z4tA(cEZ@a3gZ=s(V%1z5=eMjKf6Ayf(_QLt{ncAHvotKqo#3^PY7O5kiQ*s&l!ntY z--2U{i53^n2aT;)iHv$Pf#PBiiJKJ>D;C2bHy*;Ey`@eOsyD$HgB*wE94+FIT8?Ep zkJsnuMjFxXJYB|Yq3n5 zvI2=pnYjDyc#H+6l^uV3DL2GH!RX}PFhcHcgvW}Mg3zL0G z9?toV+Yk9OW6tc0y?JAPHtjzimU>51QwBY46eNpAaZSzrVZKsOVFB__hdX4x9rp(4 za{YM%ZQ$crPCyyx0+&;aL+yu2UOer5#P|qBy{w@8w%ZG%H5Q~EVDNJC_ZXI4Rzi#S z1mJdQIDG{PnE$=+Bpq!(+h2yAOx;K6C^C6973NZ}5NfaburjnB`(JJAL5w_WMktw} zOrV1-Z3~mbOSkvQxAR!;qG8-_6F9wGVGFNxi;8EH=lc(H4`IuLSE76&W?l=I=fSAv zIL4vH;)3X}viHMjMYNdvQDZE>k%ue&*YhbTz+z&Vilzt@w3p^NpPXSgK}jq!47sWP&$g{ zA}g3vUlO)3{f7LE3nZz8NCLPO9{5>fr49MCBn&(17LjRK(D39-O^2UXE^fLxCPkwp zhU_OGl7vbKE8r0A)`+AZ89Nv#`X>!z=G8s_L4RW%Y1K40Pc)=9G^83ujqy<5|Kv1+ zb0w`^+4OQ0{FG#Zmbu@M_MZ(Cfi#moTctYh&6SqZ&b91fsanus%`h)|0FLeiM>OkGS1k3+Mvf|-#2^3B!Zq<2A z8FEXC5I5f>&MqZU3F(P;5J@3ZpMVujClLAt)w2kQmyX3bq>TNI!TK3n1c2gqGj|fM z!#=6!2sTn+DBep)60@OOndH-FI9`ZiTYAu`A zDTR5Lg-?4eJaVGDDrlB)>FXC~jSOdrM9lZQ9sj_dKlv2d9g z&{c)7&~i?NXKw@admfy)rccu!2v4?koZthDiA7qdT=6G;GTU8fsuH!x-L*H)czHsM z95J!e18Wd`2kmCz^dl6-wNnGzahhCF9{^__-7iu7v?RgW80>`++Uf-+Hz@X`sn<)% z8w*%ZjY-Yjlp5RP8vi(1#Fgr%Vm>`ITC^T!xS#S_3PuSYrC9l~wy{)Nh@^l5V7h?2Z}wz0LMOw`jNSfzMRsDF5s^wvb0Fc z={1O0Xw-Ft^_(FQ4g&H(*0%e%x~3B3Xp3{7Wa*x3Gf#FnWy%X8C`d{wt=P(*1!CEHxXcYB3?~TH1*B3| zJjmf%TSjczegfVPj&=U9L?2Gj*T|b!^^e$vEOP0TYMiz?U;?o;6qZpzRt=iX1i)*2 zW|S{TfHX*4<`-T|Iz~W7KLqw0i33BF@o0(wvA~M}VG+ZwoRp(6qZ!h}EHm7gOjJRt zJ2wUcX#{~RtdHM}r~=J>9FWr+Q>j>YVG}v3F<`hWF2`&qcBPXNwOQu^|FclKP+LF- z@FTGea!1l9c>!*|eX>rwwV!Iw7#;OZedFoNBlKbvI=?v1S``x|+-q_LaoylICK+0owJn0HN>J}fjVmOq_0#=vH4!o>pt)@JgOXYM{_6_PKPJ_ zD)u#93Du-krR4M|A~KgSAZ0WHAV2YBLen*0rHvlAr1nY*Tzd$8y?|Gja~%s;W4A!Q zGanDvyWNwUm&e;Vx|+6qJNA?g6~?Kd`oof}?S--RKrY+Pqw0w?ZHtt*flFL4NE)-J z%ejhuIoqxyonV(xA%RRJcsw7+o7-jbn%7F<4)6y}`K)~@2CtEIdu*fgrCXOxzzd#J zC!Z@WXIAvHboW9oSr-1+Q6D!xjt?*QFCRy*hbxrfudhF_G+sk)80THYkhf;!ps*Xn z+U?pcw+X@Y3a;pA4Oy^RO{t2AOXO-?<3vFD>9a><3f2P*C2f zFpv+5+!LC!_T?VJEx85%E|krWBK^u8(>&-KuB}T)=-8ly6Tno9{bw6P7#jA-M`a~V zEL}PcHNY^BOMnI@~Bz$pYu%R=Zyh#fN#~NB65^eNvi{Wmz6btOZ*QOV%YA#0pLR z)9qHC$;NDJ$`VLFGYBt8|c&gu%l3SABWyR_0BL)Rp9t&rjWmMtb+F;Yf zBXb>cwo^i#lSGg=l?5DSSJM8Xa`;IlX*2DLoCX@R3A}bP?!o%yk|&h|Z$qr~RmRRZ z5nnAeV=-(OTU*i1o)(eqGs=v=T;JrnCVst4|GF?i6H{=KuU7z}2;TqpODahD4IO4a zwjis`jO@p()DZE4pwl5k@fJa^;i{QmzXXnqn5*f(32kHqP39VP%~U_7dZNAwo=2;j z(@O2B4aTIr(b-d`42=YY>FQ-SLX;K#+PBZ8EXc zgE6g(IfK;{zO{nu8dRz|4p8y}$U{p|C z`gU|gR$s?QzF)rVEkM`!cRjdDMJ0VCcrir9w0oY@Ufat(H z0m*(HjVpobc%vvT>s>@iwz&heEIFDd7Ev3bpl-g6e*+88V(eSubr;iqZ?E5<}ZZ8WJGq=~Fixneh`5KIVJr5gwFj7L=7U}=KA;(SF?O(J{Ghj0x8Xy8T)ndbWl#zq zOE;IdlRbUQJ>ns6|A+M%D30nzxG^Mo@tsyXW2g{eW75ce@ms{VAC2I3YjG22CkHlN ztMX3-7c{Ky1VaZJw);!EhC?-52xDE!*W44C6F~lPK+!x z3rlin+gIw1uM@hTOZ+x^*nGSEB%z@QfPs8c!{TZmPGDHqrux@VxO$NsW9X#}8vJjJ zQ=Z2O`C;{sOl%B$tUwTdU8Fk3M%QmIohBGStlw9pF{gcJ<-vjrwf3!h6UO)AYzh z?Stc7f|`Ym^r(3wN=O>O0xkS_*}5%p(s&vG%NnrVROr(y5DloAuEJI2Qt*6E+#Q#j zT~D$FhaCLRb8w687k@jxetyi8fcgo1-eJ?ce4o_ePsAOU0!`0&iE2qDd4QmOMR5yNSSE2t1x^$XiFf7o3`&$# zm;fUnufwQeSegmjK=EjfRtk6wz4wGsNdVgY>h{}n-xBcBXIEG7{>0}Mwn&d;*%d5d zP$#JsJpVi!*HX3+$~-9K!z3C@)XnbW_A%qR$F(D8=;n*YSAb`o9oBCSbB@hk_m}V^ zzJCxUxM&Qs7S8~*^x22)caXLD5`%~DiudQ&{;tCF{`+&u()0Cp)_1-&&)bT(tDf!d zVqXpQ>}ZCn7_oJYFW<-P=gsXWke|D;8F;=c@m!OG1oScTeSa>v+Rc!oF8TGD^O3`~ zsR~^J?aTMmzFWY@)xqQDYWDSOpl@vK`dXmdq1#msMAw)1?eRNVd3jxqdVD-8{Nf0g z+-by3eHR>M$4RrR4fi16snX43lxZI7_bBHRXRM$N?|N8!a06pO=CAP4BPIYGDvkW{7mR1*$%6_fu=r-t7rpikD{~l`eH``q}5*u9f4C zcD2RsYefDheZa}Uq4#`ap>>!sm5^M!x-<@V(OJ8qt3{?fT=$sff8*+%Vnk^hsLQr( z+qP}n-KTBawr$%sPusR_^RzMjev|n#Gq-hB^`ufsW$(S#0Eb^8t#9I257G=V6W z-^n|SZug^HI~YQ6`)nps0=p>}g=;eWDEn+zPd)#6;yb+P{Q+(Sr=nwt&BG<8)6U7Q zQ50@$S)VZY5iiJ}<*hIV(N(h98I>V_LF$IUyTK0UZhu)6S(~Z02qYeqE0dcwo2(2q z_v)^5|CIxuWFF3B+9tcCN?7J@WD(_(6?k*l6e@BVcrN_cBCAiwV`wUO)P8sWGwE;E zM84vU(Lq1%jcq(o$P>-yOpF}#(3YN$&ns)@GV`b*xiv7dO!J2LU>u(~R zN>;fc`h3ahxt~@)K|bhSKe0Bvl^Z;sg?jCm_kv@bFo5p`r3RZIbN~oS4^6~4iTwe= zP*VZrn5WJL6_LsEdFHRBvp0r$Cl71?;M+HCmO0fB` zhWG#)_D+w2!jByd$O{LO1R&R{S%$nwguBgStRc267)%o0HP6=9DMA*X5mvBTU!H8E zS>RyFGDQDc(;5M7!2DE4!gvR-r6F0$C30wRV9E_cuF?4NYe^V@`T6T4L4vB?gspp? zyvjrxv?}dF{Mwt49|C}Eql*MH0K#N0F&Bx7oC_kbw;;!@sJf(cU201Da#TWfjDH9jOR4+*Ul`M*xTqY>|^!mv8(ZGtM>-3R7w9k;vrbUo)8`0_kLnEbJ5O=9bSq(q&GQ+=j^-;+i^nEG-rc;}5?yjMGCr@MJneihO!-hW} zt18t7P=#v6%zt2eVh|;#MJXF;^;yMVgVVIs`}DskMsR?;`yY0`{xdhAIrOgBHUE4E00`-aiZOcok+`>6FWI*pak{SO*L7? z^4LKbo!i#dW^I<9DF1w#>5D03LKhF+49C}&1JWzn~t|B3g4KwaqW z4ZW7mcen0IUX59@18ApI7<}qR<7$OPkOUD3^`*mx27GXD%SyMl_pzjKaj~>!9qG^) z7=t*A^y7%8Q35RpP;CL>ZW%V(a2l41$y2EyKuW&;MizzOBe?TzkatR2dU-`dSdJN} zJJ$=n=hZfcTz!uSRum#=eBbs)5FtiX40AIT^<##whktX!3R89KQ$jGb$^HukUNA)I_F*kvj zxa)@Z1C_Gp$Ut&*!JRl53!yR(k&R~9%Y)=9mjRT2FBE%FRvOB1H61 z4tW72BC$$6YB#N8C7sbR>W91Ts(tNnUL~j;Gdc7Bgl%&d5SEa(6DkrkYl9o##m8R zu2a~g(8GX%)u~dZ6jTd6xR7WGR{q&}!NeQ3s9nPap3r-6b{-{5{^2n3^HEXtX1Z3( zbe2;P%-&yX&g)c4P3M}&pPHK~MpEkoUFGS)(N=V408GllXwD}Tm$=Mb|EM&rO#s(m zHVfSOPe(2&j?=0q(wpic4$`BQmXXB1qZ0qk5|v+hVV8n5^qmE#j;QXfio|8?3yKh; z@ZFOE=4@B>N!U&ViQq9!Xi~Nnr23J>5YZ_ccG_l-%W(?EUyoZ@+-MR^^9|cm?BQ2t zu|gA!n8dNXbJ&d~GK*vSOcjPuKq{C%CX;~Us-<3?$&_+_+ZU1jZa>3D!_Wh^L;A?* z9_LZO`$Nd)iqw-Vql^RLWgLYa8`r&B3$j2ZKN{r}oyW5UrA(-#JSeVukVd4{x661~ z>0;B#i4KrYL^8`>_i8ePO|RI+kg=hA2Za~3b%IhlwaR@uwe#xdD32=XB&#xu`?&>h z*STN7%SGjQ{Ev*KwkLqqLckp&1K7R6zSBQE_hV!`Rr-RuL!2$-D<~^MGupZ|@Kdt5 z>rEKxBwX9|5YpU)w}3GGF1iQNUtAz5guvMj#`n4COeBWy_=mxEoZpXQ=dZLU4 z|K;*V)QX0FMWO*G0xGOmHleI4DKMare?zMMRXXo~xZTFW$;a*XUgmxu3P<=~-xf}# zDCvc2^Uv%7s_cxF*I-kXGKP_cz+x^}iyx<3CR#g3r1}UiyZU|DuYK7&2Z!6mf&DN> z!AUa2*c?bMb3l--z$7sBIh=Mm8#xFsUoTDt;q&4BxY~Oz@p8VuZr<-JrrG)P&IZ_+ z6ZufGuR`6iUOYtEFN;%-Hq8RVbLRGRk2#6~uUaz}^&@-Wa>{P5);pxO_iOEGwg`sF zX!Du5H7u68O9!w&SvQ41@=1-iDsfFf9n`R-^3Zck$5YT@X2QXLlJU3JeSl{|DQw<# zp^M2^V3wp9IxW($gH53f4=lSYo=2d5jp4G7wzpKCi>fgu7q4A>n9GWGG4zNmh%`=F zW*S#ok=_R8)60Fo8+^(uHPow?I~toLuZ{W!Y4pS8ZBUAWiL8OZuW^M1xqV5fuzb5@A{? ze1QP@)bBHk%$q~VxBWK0Op-RmRq74NOVz~bs;UqE+FHC*Xjekt_m$s(;7h{LU3Q9D z6?Uk!GnpcqD%bxSN(Fr3ersWsagp;vus}C%zn+xjAb}cN$r4#!6c05sF=2XL~}>T#!@fQE2wyj9DTH^$qz>-49dt z&v1SX+0LAA<5LuOOlDeYM7$rt-^QHXGiNAd`HN@MM9e9eHkYA@tSOqHP7;}^{`X+} z{9$P-!PFp5gvKYa6K!gfyReg?gxxI_u^548$|T{+*UqC6ZpYBH;oCXuFYl+?53(^m zsozH(mJsth-+`y%8%^73sjp!kF;^vyTu#9};|Zra&j7>jN>YB3>obNp?9ojow0eI) z-Ivyu?T4J^8FlnrK_w7lhvIc$v`^l_9qtLF(k!2}Tk+F9 zQkV)aL5$(2b8;9%FM&9#gY90pTPYB*WJ{s6YmE5pRN7Q9sI^NIa-)e=k}N&l2Y7eb zjA)=dgJ>`%5tkCJ`c0rHSuMG-Fl5CG)~L=$ob(9J(OU^k3o15;B{b=HlY!$WPL&`@ za<@eDT|UE-_gRe^umaVRj#zL(Bfdsik~L< z|Hz@P;C2ZXT_=c(w;(*y5yP_4#Jh70zZ09fX5kExq3EHAa0lAgh`nEfl7 zP0IDwq?($T;NuzoDk;8WVKSCQ7w+ve%+knJ?pEDyce?FciMbZuu6>6T7;yJtU}#Lm zteF`;-_NI$@US+sNt#B<2NFnhltv)L(<_-Rl+`5FxyzZVphNZ_eK4kb3BeZEE?7H{ zRMDN!zcqx&f|^(49q2KErknM*oc{J=%i~MgIM-DZ7JisP4H(i=Fl0gHpzq=q9sW+7 zQ7F9>JG+nL@dc&{?O%v2ZcieBsU1b6D71wcEkZPMxjHvONRhT5EENx0wg> zbT_>$;NTZnX?FDxv3&2?Y7Tw_gVn=0F$+ys)&CoFwl9ts^6A}>epAd|dy^Ks?g3n$ zP>1kl45J7VI$RKjK)m8l?MP@vt6{jKp*9Qeq)vv@q0DM=IUqDDA(LR&>w~gL66wWP z$~y1))SG%U4`HCtF`6lpd@@f-L6a(9HXY@Y*Y$=DM`U(}4PE5ac%mqCVVXeivQ1`V zeeTS>__-43d;%jrd>rDRh?<5jOjfPYEx}~)@U9}c&YrR#vW^mydc7m`QL6HnLAr3h zkqN{Q@gsALS$lVu#)o>E>K+i}=q4-Ky!9q8Ya5&Pa%Cn?5dQXHCxyW^vTz*|OLqo4 zrTdiFzh*Z^{J+s;qPuUMD4@<4^1NxlOCc}1As3tK!+}j{fxW)!{Si-eSZB-*XPb}R zAnS-GZ!Qg-{0!aGwkvA2y?14``ZpG*L4X%`+7ye~bE$_wR4t^z-cL!0v#> zYYlzJ_%>(U6a7pbK;KX9Gbg(#BB>;N<&d!QyG6A{Z?2_2P?}k1B>hS;G0m;xj5aC$ z=yMi~*;(kPlf`2o%`q~mC04j`uKxE^d%`JW_T;BZL`2 zgV4;f#fuO`|_~gW6mk=Wm;Ey%3c?BC48pf zIxSK%(Tg29rr9cRr5$3?VvXKK@nx~>P+j+NkwWB$P|0lXqnD*_;7~ogSB8z$jBI~Q zWX%{87?{^R3#_0AMyx+rRaA8t=Fy7EBhoM}Kj=tkrN<}GM)NM%BaO719$B7*A%B1R znA`FSj1|l~^)z*I-4aU9xEjIf?C&Zg;JP$}3UUPa`WV=6X@4wuwC&p+1_aK?sI`0R z?l^L6P#e)bzjNx`pul6lfWH)bv0UO^;7AM++6)G0dd%w$X9GYg@&!0{4V}44fq*@v zV2(fM?>DIU^bI0&0&|RpZ9(Bc6pk>DtdJ|eT9i}Qalx%G%|V_r4Bi9|h7OqCXsGe? zTkq)Z4$R-f-uV~$3HsNU?U$RCG&}B^G_T!%a_$;enw<&QzNRdn>d`qqG0Fl|6JItC z4NSs78&diw{?*MH&T->A?3T&Q1A1=uO~~Z$rNh?ygK~0= zoyrDt3{pRPX8|R0op_>cT6?vFapK@*Gv$BEOsThQuumkoD4kvK&RX%c5OSdQP7ll6 zZp)dqap*#fYzpNm1g zKNanIS*zrZIKO}*&pVp(LV5ynHA}Nmuf!|55fR1rr!(G(0}KF?wMk;|66*PsEL0V- zi(BK(PX6|5F2Iu}A;^Vm!jf@kqRmz&ZTE-XPjG!cU%!i1y%h_^yAi-Gf$&^F(~}@# z9+M5t>-G%qG_P%_ZY&;++!f2@i*^#n+#9mFqiOF+N6md8$#WibWay9GAexRM!rQF}8 z8>a$CA012Y888W!XJH}9aG|>?TgHzM5R0kaROhR@7qI`nQ)R zWLlq*_fX>*JRyxRCcvd62b!6kFDIOw=G5@}ycs?AZeB&bZf*r;{{OSq9`nLg+ldnP z<0_Naf=6kJv5-N?j*Rl8 z|FYI@O6f$o>k+urG=N}(G!_JWSA{MhU$h_<;0b4X+O!>)AojCfELpmHOYO-bK~EHY zrCuaDh7i%4Z}Mc68c09F-!A(z=6_XwQ8D3 zbP(u*=Kr!*G-jhvQP!1Y&$4G|DZr5M=H;j99^|z{P^HIySvjzQ0O+y?p1UWj@T(Mb63Thm3HFt^9 zCMtJe>ASNVVLQ<5>>0%H2&a|3kwjo{v>(}2T=t2^oqpIoK+xpEKmfc?rrSAT^|vk~ zZ5`UdV3#~!FjEt5LEp)@p={5opmuL1#TrZ0l{zt_JX;nL(GQuWB{1&!gJp0}nSB7^ zM?}LA?P4kz`t@j@31Qx!zdkh@E)D+sWuqj+0uK=fKV7t+yM-&9ym3ZC(-Pp91=|8e zYDM79ujm9{UMH|VfC@7i#*1Ez>^kgnSi==_*O<)?05hP^7}T}UHiog0zxFL|naIlK zz&CIb5>1%&bO--~%<^e3z`n@K=PeJT=ZIc#9&x&DT@X~qkdwS>Bw#g05m#?jddQ~d`2q6|p%~=zV<6PX_^9a18 zGLTX(Udyw48^njc^yQA?9gf;3aX zEjLIRd-3!Bt6H^qIh-FaV=o&9>oi)2Nwee!LVU*zKMVKIQ!K_c48O@q<+eHKi?92V z<|a8f-Tts$DIVk_&%_Zm(ONd#;zpNdJPs!uE5-3Jw@~m3DW#iXOA=;zVZGD#?-909 zz>@;}qaFWdDwzEm!swV`Sv|pZ&y)n-nI2oc8S?x;LcI|ZN!E5PhZ_(jc=6*Mkm}Gh zxu3>{xOrZ7nyrIwC+pu$Q=If;ge^6WJGQ!(8i&2#+u7Wvv(E!DW%ygf=eqa!@aFUm zjsJB!*@MpiWAO48mBvl~{Os!btHyn_emU*=&xV`IetpF}jO;Y~F-Q`b*zG8Ki+^@n z(e`fAZak?>KzhWj@1hpz7qfGlVc+F@-M z8poKUID5I>v>a{%7$LUEf-f(Czcag#!!3dfJt84r5N0sl;>ca-A^Fd5#3b@R!7Y;d zre%8yVdW$qaRJ((_2fg~=$(<>){Sa6!1_T+5on14Yih;&6|2Mp;0C!bAeUdtVGPfeA46S=IHX^cb)=E=dnHV;DTL3NW(1s}%DLlcR7i zScFxk>6+8?C#-+7ium=CH|5JS*~6kVx+Uvzh|VyCBRSqF=R_luCy35B%LTPQkTUj> zb?9{q51%%J)o~0k%o4Tu0j7t$BzsG7K=vzpfXnp~`or2Up!HQ-ZY0@El4V8{X49%; zP~KVK7>I%vsQNknb_MW_LO8-03DzBvRYdM`oUBYB5};x}-^hEkLj^4JK^fV;rOnW^ zuxn|p(B+>lj~}!n(g@ZFRU*oml#NC?5kJOu{rvD#P8L(CC{D9tw|YgfWDwbj1GkV5~ z@(YuRBVWbDM2C^dai@QABdp|%eW6jAkuOxd)45udmF_kL70>Dy9MHB{w&lsJJ{N^G z9-vFHf1XskS1GFR*Tjq#g{V?w_caS6n94UOEM~l1@W6(*1QI=VFBXbEXw-gAdk<|& z;8h;{eD4QJeiq$Se1Xy*9H?(0z)?ca+jB_>O_e9mLe#eHf^P}ZGyR2Y2c@}$ z_7sTdxR=p#?ouGJ$QiN7-Ll5mA&9IkGg`i`z}Im<=XJJMxY$4*YvqxBQ1ZpJP#hN#bU_3@oJoU&db`d>0|>3V2nn6#{x5pl-P8*~ zPca?$5vmSd8Lt(v{2-$`Y2-b6apvmAD%|6mE-V%f9QnG&yjmG5B(wXqbRJ4CL9UbI zgkr7Hc|njr!F-sM2RM;vOw`rIVR7>v8VWM8jD+;{(LJV=3qUOiJoT-Pkvp@}E*#Lci5H5uZ0DK}dqize0+jxQT62?9y~f+LhPGsz z(9Tckf;jbdaBL@UmQ>V=#RN(&hReLClocf{p<@DLl+mDPe$RT_(=1YFQC>S$hRI={ zyYB-BfGv#s`fKas7ysYu@3`@oUhC!zU>3b3I)^J;^uL66dp?9N6IpVU@gS@C3MfzN zWYAc=%L99H1Tdvk`jQKu62}AWXfRFkv=~x(S`0er`e($*Z4qISnimNZ;e1FNq>_>A zbnl(T=}pb94vd>5?<>dmvxSn%gOY0X(asV0xe>{$5kRubB0_eB3R``FSRq ztS`t(~Sl5Pli zW^McnrW%krYM^?GMD>Ud-*@2_I!z7q#(_1Q$4RT{0Ykg0b`GON-uw{ z)}K=DljRyiDI~|Ze*@G`ema4J6GB>3w$+r^1s#+zYh`Ie_HiE47E+?6UN zXc>oH!u)@0byOi`Eb21m1KMNUIz&|0mz<~~o4eJ;>);va#`d!gi`>e#f01^(S=VDA zqPC~%?zycdbt3>w(K^c+sK-8X)EH!&YS_2zCd)LGXa~XvjPA3g5tq#wc=r3mYB~~- zj;u3TM@iLBcj1;c|7|e(Y+|cnBasIVNu0`ZG#GxnQMss4I9w0v{~ zcx?zI^-Y%lgJe(+-ZbTJ_R$vL*}rJkQ<4KE|&(q2O@oGx32RK8@y+T(7_U*rTXEJ zw-GF4z{^NMZMpQPiEz^t9MqTCU{@=|(90Jqc1Pj-`Qg08QqMR7QMqTRK;oY>kw%XJ zs^IS9HK)tqH6Xv-D4Zp!$Om6f&P%$S|Z8W!m2auqCB=ZBJ} zMyYO9Rsi+`Jt!H*dyWzU(-Y3=joC?&>l&n(cVNz@2!P1HRMb0Y4nhT(I}cFRn#lo#BAv# zuz0({xkfR&Zbg-B=#&>Szf`(qq-=Fsgs3$usyL++cKKUU6ED3Bq=9+JuQn${A4B`I zE(;*UwKZ^z5f&sM8^&tE^7A<8NAUGFdHU1#bsU%VihTKV+-t$h{)3Ev7ZPUniS0GD z(ur?yMTR#ev|+@F#TQV$z6|XmAGhP{?qu&N;wZECxECmOgQc!ISrirHR8IsPZwL(&miw0Dc#b@9RXAwaG_FR#|_K1(c$k^}6e)6kG4 ziBO2}2&f6|p)?-Z7&{C|Z_TE*JrJ~;EH;YU?vB!3XcoUo04yCNw2e%C^#0ZhTyq7^ zoxuc&b8dk#jSeXl6fOLuIZY&!9$Y&Z6KlL|j;wAQJ)&3>x!qF7B0iP>i*7TVtMgwG z?Yh~dk0~Q%t5`)Ez?_hg|M_Lh6poTkl<%37gIF~Ov9-T1B&qB?;NIV zgimX|h$XTWn(7DhS8dRQXQe<3Scx9`O5kcFS#O04dPBr=hEp)v#)Ue`yb4xTXtw-_ zB>LMj9(d%=BGWU0ZlYtgnY7*o*sSK?6njiD$wiN-WZhf_92Z*^^|pNY#Eu4`$f(oy zyn0AICnu^JLmB$9z0_0o>np^WB#hCtY-u&QGo?eYB8$)FA=t$pU=LxR+xOG9*m;S4 zE!?_2r&woVe_XM-l0V3|s>SIf)t#Z)0r7Jc_$c8ED*CG-SSg7X9%b2Us|0yY-j^OTrQ>y7Az^=zA`Em9{G5J(4LWinfS3>c^z_?2`h5uyA2! zSkQHD-YpRzwL3}42P3PIcckl^PXjCvxYUn`w?~A1?+>O0{@~mE+tlf?IW5)4)n=Hqup0KPwS2m5vrsmN&RB^u4j{&Q)r>obFTyJl6eezW*m$!!)E=}%_ zPOdZeuh?XjN;#;$C@ksvkEu!0QTMKIY*F91a`i4p=`{rf%65oXWmp>g6aTV>PcER7 z-X2Z%UX~Q+!e#Dp+mKl|CN*?$F5Ljsm0TH!TNj+{4?CQ)luO%6{~J7b?@lJjV}zUd z65;lKBC?P#$NVKlC*L{_vfU+SF@r++&oMZxXnifStJ%@)KLXulRuLV{FBu4-qX1hVxRq+gd~mg3>J0_R-ryfOnSV*5Py^VSfi?Av{PNZW!g`w%dwQq z+-N5xaU4YJi&;J@jg2n0fd&}zZ>R&3*>!l~l1%Vl*ET{w(q%dAm9nC%h{lSh>(Ex5 zM#c{q=p*{zj&7$b+d=%TcQ*&(>j@3rV`pjWz^)!edt@1`lZC;(h0>;##vXrHYU^UA zax;7vAEm@nDKtoEP^-oETQ}hBn`d_|U*2vn9ku8S9VwLt}jD!kbk@cRU? z)3#sgY+T+q%Zfhdai!^TAD`4KODMkxvlTX9OV%lj`C5}meY-Pp`=Ad0c-Ai|;BtX9 z1#o`OysN`~v-BN`(4cd0qm`+m5|uO!Q%>MuiU=N4*bYtw5V2r~Bty&|(R~7TCR5W= zO{Q*^Ix2)t_qU3{nm|4g5wrK`k0iv5r4+QLXQMepez@cr z^qM7CCwuZShgHq+<1$Rwq$sKi*47BO4LFT!QdDKi?nQI)SpohDNT{c*C(LFoR$edL zv67iab0-=!fGf3RpfCbQu6b~6T-Jc4cpoi8HS6GW(kYU&pzrLpCmy5HS zmUPliv;nQ z*iJL6*DGHMPiw0^yI2x1EZQ`gDe+6mkI*SI!8ED8oClHUG-O8Sz+`978Kq})pl-!U zNj{uARb(;uIA3;6K}JtxPr*K(M?{MYOylr={9df8JyF%q(*We2m0)4K8~}8hV?#jb z@OIw!Sy>xE|HskPco*MBRO&xmPlp>BwddE6=RzBe*(PWNNj442Y|^x>7`|#5NarLb z#8cmD1)7>Uz6+it-(}W3JD#9@f}-8}MfWt>Y|mTpJpr%j_q1oYr?+8l7E3XJibwvB z<(HU+(M@K-yoD-!0omg}{}_ml?4mkR7>%C^R0%_i>;A-y^REH2nJB!wHoD+4>EI8l zqAwPOEiI#an#*_(6WfKdZZL8a%MjaUWhzRF^{+FSV==y@(A0|j&}f`9sP%McCpHEtfm=saVP4>n0>R5_07$jdvjohq=G$JK2|m-sv_pYD;q!omMUPe zYF|~gA(6UP2U%ibn)4zzT3k!(K3~TTBi@r$bwv)whVa*pyZnwDqKNfW2S0?0^QTQ-O<%lDQuS<|X|+(5{ydb_zX zQa~#syGa7AwjKnRvQ-2-SgQBbfLN1P3Y%@1Ta&$jJ_=9hXO=jWWM_6m{x6ljDvq== zdCvzDkO8FVQmZ;4C-|a^mV>Lc`cd5Kffq5dgTQj1B{mo6G&I@_lo#6vf{|$=IZMvAIw8IXkesL`VO&v06OfKb zl2jgeIr{w5fFkH4dW})5`TLSNqr1-R6XA?BmWD^9eN>v#Ke~6tzWR{&iCf8y+v-)1 zW0(r?4p_u=MNim=yig^z#*g0DEq@h$?^D@oCSUj?%umwv`MwtW<4Q1l`yC!W#=bsY# z>H-@+n6IGTX$7uar3scFH8hpIQ+8!?0DDRjn0Z{5!1>*(!%ab_n;T#i1_n6n){spu z1;`8rP<_jI6774FY_{K5OHwDX~LMvM9qV z^3`=aabnuWlm?dwYxpR3i{vRF3XnVTnt=Ur8dPpFOY#|atJ#u?BNg>1672aVY0rlH zlw1LURvfUdko{~z-3^tL-_mjw3SmN+=2yWuw-5%7Zu>EFsMhC|N3dC_wAR}5tfM^| zHgp5ZIv+Pj@G)SnJ4c+=GjtekK8)pzk`TZVlVw#8{2X%_PF|B#BT*z&r-e(rfWT7kDWVNc1*(CqkDHj2*(N zaQ8$kfriST1Ah(9OQQW@lDN&4T4#uERd|>!h65;SVm2-?GsAHj;!_Z(f;p4@l2ZKo z?ZXy5#Ed(2D-wjJ+9L^OzJYQ2?t%oF(+sSS<5Mu+7it^y-3yFlzb18wa$}jX^D}j~ zNV3aRcis&KNL(^^28li%nkSdFqrJXOlx8uYd5SHnr9~iMktAOP4>>_;2(WutyP$|; zS{13$pFC`Ld1w5geRWu%u`D&IpqvNKO%(8f^tZ3)@WfnRz##$jM)Wd!WHiX|na~-RK~-O?z3& ziv38=I>&*SvWd!@Sxm`KAeT&SWWQyURzdmZuGhkD|3{b1_;-%yAC`yB3S{g*uJ%i& z-bf;S>$?M3z+j}*N?ME7exi@s;Sdbrr86_+WY8E0l6VJ#vLFkXCY7%lc?p2rG027` zcT$^*yAMcfK!4_ku+1fEY1-X~nX>fmh^To2D@NFHl3Dqtbbd#uzk60l(Fb=tIKh4A zm>LAbxv?4>9UQ@!7G;E*OG7Ha7h@=zSUIY)s;wi|GTU)wm8KV)S(C+;+a3M=AsY_x zN9<8@CNSGvrH+pYqZ98=G7SkaJMO&}`$?K++5MacWaMNDCNbtia#kHasKXI6mCaPL zlZ!}Vj)SZ-g&Z2LGWScfbwo}$;*#4Ww^XL>dlhBI6!qwY72)^vkjVp-qcB~yD$Vo1 zC>Sy>J1aN^2^u=JL?iX}PofkGt=8v_*ptaOLqrutkK#>Km5{SHYxC4n%5g=#=#OKW}gIk&)7X1$B?y&p@WxS0a))*vy zSbW6iYoj@7PVt~fZSi+oG~-fIp=`e$G7Jau@I$y4My2c}ZS>+VV5p_~>JZK;aMB0Q-mRl4d?tp&aK1C&z5^R2{&xYo9X34x3SShGR zJ7e#;MX9?Y`0HeH9I$zmcT;Ky#_&&(qmWmn)`Z3mby{*-3%Q_YuY1{vxwH{ukQ**2 z+hu0|W{s|xx1_+DN5Q48o!yraH-@DIsf66d*VlUroVXwmN{X?EzFyR*p3y~!!0u3E zwrPk+F$KRsLmZXI7S{$Vcz8B24!LH<<`$&U&(EM!#)nYFy!Ac_ep#YhwoIK%p=~s^ z!LF@Bv}2(g(#?Hy=&@asi^ItUsz#8)f;mo>;emM)?y3%>jud)LYjMFo!<##y5h%Qe zM0@~?=~DC#0|)(aTSoU%K5Y3eANdvbZlBrbNdE1>QEl^qjggkqZAIh*FeXB@%!J5Sd*T+Wbhk46^LwoBL_^ z#q#*$gk^4LMAoDLtvkE7F36_l zB1$<9I|by%wdbHus>U;hZgfmZ2)f ziWt|-zG0j?Ngz14-)YG@rAMls5v^l{88|Xq7_kqa(=f$7Cx*kqo`J40*Qrq`G|o(_ z1X~KLiLiWOQh5szOxZUmX3PmVm)Nw=!t?ViS^({dB+it~2r5#B&-UJ57naFD53V^zg5hZts0~(Om^%R-*tr1{^o#Bfl5h&1mX)t*voa*~r)UFX z>4VY9J3S1nSP|&T9<1+8u2PIM(i#^o_#)$8co(Pj5%worJ#9A+vOagrL%t@=M@Z^m9EUF7e`{bj==<@Xvme!rJ_|x_nZ#7#VyG*V1E|J?#b9{ z)^*ezb_^0sS58d0yAyYkWfY}a$ki3pWWgqO$-{^0fAINn9yoNiR)=q2j1u;c?S>q0 zg2~XjVZ#7PN?hy5KpD8=^*rpUHH=>ibR-9y-Agswytw-*G`{HMVO})p^&@YTw5W=c zw%p=w)k1^L9l#&hZXEL-W~u#e^&iYU;J)}a#o!5fuwAuE4oSx>vkv-8U&Q5AHI+Vw zND8B!|Ex%JM|36+%Pv`GX3917KljWp5D2v?OZ1|?6LnwMoO-<%$H~I%jMb!CrdKQ@!5%;} zXntdnJg!q~1|}O?9SgUzboL3dvVTi`7ttt?J``^pXlUacho%`jEJ5}Iv$JbKE)-hF zAd&BviuwGDypFcAdYdFZCY|;T4DNvORhpno3!LrlJyNOl(7h6nr&FwxJ|vY7MHBxA zl`80lg~Nia)_`?@VmY}=-0VGVBG8yQf&)f^Y-t&^U?x(v5y%n-IxcmBANn@N_2k$} z+@(?f%TzFQEt%p`X%t4q%QO&2PR1)!1!os)JXeq#-6&Kxp3fMKW&|+N46Slk6CS}f zmrzqnz3}`OAA@Q1g9Hq4arqArzX}YNrch~rBU&+wG1Yj4;lD>Q=73lzl)(%i`Qw|P ztHnGes*}tcBmZ+-h-1blwDFadY&#&F>LwPPs0K8V}(6~!-fN1=82((GrBjq?x3SI z@2TN<;sEHW|BNH7;+>6_vmtM$RyAXhdYy2@vKI_6+@^MmYpQ}!P(Fm~4w~50WXleM zwtbyzKp=CPG^? zl46F44*xb4=Ic${BDfTa=Q?`ob-nufNc-vOt=2v;8D%XTv-r9JppLzlYUJNER|szV zt2-Vd-O*{LG4ye2D1NK;4@qg>0Z^zK}-nsz)&lCSjXHHN8w{QqmE;R=;TwA0*1!s#efAw6YWIDp+L&-wU?-H zPI9@XGm$dX=}Z_HTXvOnN}YZmOLyvp-2^+bJ+m7I)QVD|5|l+vfJghFvNc)D5J|O3 zx_!@SsmEH?S6%`k006@FCaqmhmnGpvV9u%$fhnrNsT z9Wi66@K#VZ97Z5b*^t*9of5W!PJG7vqi%Yi_9iL>E_&kwii9D`dSCtu(iN zzD0`$0BPt5*Ikb}moZ;&ZcaIk3hmk8@23#Alp_U_Tsgn^Vu99r?1R1MtY*vvx%baU{rFs%5sF}qxa7OXwllOMr=UH-=g9_%)AR*iI|v{Hh#;UA z7k4-bf#6|taCy-57#_HWP<|j@&XM}_RK-0V*@Lu%mE`1y43@K7y2;`(-z(NROJmJF zJX_X42sQP_x~d7ouWkP zp>EN(ZF9G6+qP|Y@3w8*wr$(C?cKJ!Pk;ZtG8p^~i1s7j5@HM8as>u7fd zX6)hha}2VXk=c7TStjv3l8qx#q-H|I;nmgK6`fxN(S@Xfnx5bc6Rw6~euX>$6o0;7 zmICcHjxd=v#9QSBMSPxjSIZ?1A&Gu`#BNBJTz)(fXZq%HLHF^D$4ur~Mgo-F5^LLD0O0GTg{1 zsIFvlo7O(6Qd5~&El1ceLA8JN0FMQ1W+pk_GaK9bN)=_Lb|^Z>hlZ#LbV2JJNLttZ zc8zm%%N*RkHC)id;@7<|3Q+0M|O+T&OJaS$6j2C2;ErBqCPo(`NO_?kj3!RZRhq6lKj$|8!Fn% z6@iWV+`f$@0qb-e-n0C3#u3$UxN#MEi~8b&x;Pgp@|h<(j)96uQ)anfBxK4f=|s?L zt16m4e8&fbII87sB|>X^e4QB(#jVMVRn=yKQ@vQ&bVQdactCc$c!d0nO+h#%Q>T;#+i&O}W>xF{H@sWI8O9iKA)dgj~RaY$O{)gLr$>T z+)hHh139Ai-k8A3SL^(Tr4d zCvV;KQHE>1$&O50rsGCq-|TxuQPksKEf6RAdte{SG0w3ILKQXV#}L-~f4TylGlhX& zblze}oe6%>ZLoGrbFdNj^asu&odr zwC^7Xx*@_Y+t=wP7}>RkIO3kNm&Xd_ZWV5@L?D6I=UgT3K^P`LdpH1YWO?RCh)?Q& z#Vjaw9UzrXxZuYPz^#ep7h>%~gUC&-;#nPxo(}3l*P|ezZ<0TPZ8+6f5s=VRWJTY= z|2E3Ad6{z>Q^+VhD5#`5WVOLSa$kJD*yN8`zZ~j9`NG!wX?IL-282!St|1w{8MQ7_ z)YEHVlDkZ?;jWj|1wW1k(xF&DooYKj`q=aht0SLM?^T~m6hApmsJkInK(=4 zR~Q9Q)xnV`FKe=~l2$f*qAqFLprM%Ek&XoAQ<#FuNlb8H%&zl>kINbSkJbg8aL^ZfUj?l$HVRLt{T)6uzX!iE?7(kt z|E7ozZHHyNk1*)v1By)2L!(vjsdAID^Ym`SX=xIv5{_U|CzOH7$7-e^v%pRokG|Fw z$bMED)wOjvY*hDYVml0>kQAaJicTWJdzbs;am0*hfZnIWD|4tToG7Q-|uO>%LEaru6JtzL+_{df_Ywpi!!&Tbwajd)5IEHD|Gbr zj27)tlc(d84cC{i_iHCT9iJOar@+gY8gBgk(i+!3l<2b4c{x9S=3!tZ2i5IiqmH$> zAgx1Y>Mfc&J`v_M-YO7F_~%;=P$FC^fW9FvH{YxS3QlQ2XI%SX@bXQEad5m#u7aod z)W}($)W%C?_;X~>y8eAh;%zD=#!uw*qY7G7==B1 z=FfSSs@-0(QM0R^tikT{jXwNP&qbDZ%WIj^nzyv=%-AUvbIRT3$~qU+2!CEEwfqWZ z9s+nmuS8IZm3CMo3Q# zbP~=VYWAvMI#;&uai^fju3q|?GPn*`X%F~m()>LncnZyQh3nswL;8QXfwiWKoh}GU zX?$=WYg@UNA8jqM!~FQc-k-NZ7Gs0kn2pd?jT>X35J7qY)mKK#yrf(7uv3TTDdtJ| z4wM>`L=+}6oYzl+8gyJ>fpp^Ir*MYXh6p=Fbuk3s;7&sKjA)Rpw1;34CGjG58 zT4*yqIHcVsd&^Vqn;{SCGVUf^o*AlLO)d!xblzHc&A##^Dg13MUHfp*-u z6$^})vz90L41d9iFJ1) z;^&MQ=q69)o4ndwOxIy5FtdsopXxPp;No>Q^In%&%Q&9gFRPg&#UdG7W&l)eERqcd zO-=VbRk0&C2cE*sY;5)$|5!~@0^qfmAEO9QHa1q7dku-M{L#>z9}uK(c7GzDs-*l- znQz=|aZsEwVyKcNm1p*BQ%!b!U6!V7z4WSjPLg3>9YNu3W-yWU#xt@+fd`9ZEZG6B z+DM}u44F__IZ& zsRmKfQiB)ltn$nE_HfZslbvvQBpLkGzvl*_Y7_P1Ry^9&U~n4pOoqpmR5nBORW!@o5S?tVg{u&ru7yj{7(jl01Gjn5 z4Ao_JYg?%?*+Z2>q`{svYW|ySQ^{&`S1zOF_%HUFG*1SEFE7(iJ;dGC@dw0j>7-|S zi!YyZHG{GZK}*j+olUXIXE~>p8krL)4y5P`mib0~mPa}By}7)XT1hXNKXz-WwQdbb z#v9eSxm<6a(!ow`G4s6*q~Qgd4FaY_>}m&Ge|D`4+5?{_x|u7_~D9gVaK(b6ZgqwHgJXNF?+O`b{gHH zO8w((DIT@#!OqmR88}qRyggaM&xX87n1&yVDwS#uzK7EW%{Em?o3Whv`Q1-`H~8j!nNhxEtFpzlv{drnp|i&Fc*|HJ~}0 zZFED$z8*Lg;~ID%Xa6OU5aX~OZ-~1H7O$4EbIyA4n(nxNR(I0FXc&n-UV2u)+>~e} z-{93|YW0F!uG)rN_^8L~mgUgH?tNVvsr~)nqPk?k|KgBl!(lob=P^r*RMpoC4YZTf`SO4l_Hv5<`0Ii_Cox)w4jX!4sZ!6I|$5`>BITlS0y}i03c$O;MMp~&MG zn?pmS@+(=aC9FubPLZ$;pBc{b0kXGq353ZlLhU9A%$R!5+PKS^IaivUJ&$ipS$l~^ z_=0DmsBo@k4y3hSt9%G6fU<+l4o&gq&QL@exkkY?CKgBkVVC>f^ZrDhb@ zqXRxg=P!e*M1ds5dY%cqV}b6Z-d?lH(!1_L6lEMF04~%~M4SI`H1|_REpBaj5k%zC zZXpC~Ln@;}5QixwKTulriy}mUYlxj8mYgPWMgIk|p_S(fB^wpHnc*6}@!@nXLy1-B zW^SG|HNw~mO3)4WwQa(ShATgd4yiGphet0#(+x(Np03jT#6iP(8~WA63c}MTAlYI< zrb-xdhbvx2K!!I=P7>DV^3=orcQ&b9%zg9?u1)LXgcUD^?;rm_ z2+S+VbZpp-W-xXD@6COCJ!&Ay`;IrU-!^;f%utNTWPG-%-YrO=874#=P5EVn}vD zmREJgC01R_jpz-Ul;r-1^sSzvT*7Mc59QBuk4BP*yBf!?)!mzSH9RE z!#t* zcQ5qr<>y{DwFUPC@B)uG_f6=Zn8t<|(ywoEd_4QcVPe}Bx1s5kvzSp_Tcxa-7NpX~ zX)PNod(ML!C#{(2wV7bw4)5K?YWypW;df%CUZ1yx@t;@sm*Gh@F1nZh4te>kxqste zeeQK@g97z9e*0qF|1?wl=&j!SqRvJf^I5iipI!Hu>F^zBB!9X-{9K^Zz35`z`@+Ba znxR6x&bGy2zc|tVa*EATwS4>RR{D%%#9V*Zz-)IIZtz&UB#Xu|M1ZozUO=y-i)c426@M53XILJ#%|}EUZ2t5UzJ=0sC`bVf%lNYTKgn zVsEwRaPkuaNJzrwA{Ac~*%9#hKeGeF=*HSk5tr_YKXcHHnf1MHbEdzapRcZ}@#plv z*xNVo>d+Uj5)TIpUCqR_==Ck{?b#s~mA4@Nd7``O(g)l<21Ekp?C%udQ?^M8KH?7l z%A^Mc0Bh-D>6x|)AOR)$fLJ5zL@|MC7&_6Ly@6KfpR>TtbR9N^yrc#;9yX%&y*|Bu zrY^>w?$m`mfq~(}8VhPW;% z;TQ**3)d2A-sUp`*aK&e)<5a%4puU}3)bF}5^P_xk)xvut(wZ{rZ6VdOK*Cc6 zjP@d1-3J)SNa-Qx*yy=V2|UsTXTZGMz#yN0;wGj$=t0+k1x$d#+q9SG$s?P>Lx53q ziqZweean=PFXETaY60*_frFFEtCC1#^sRE!net%~isDE6fD(3sj4Xt6#1%#NT%q`I zs*UfZ^R$>5{`7Z|4xQiFz{*A=m+=YFIGxT=)!$;qdv?hJH9HHAN;uQKa7G7{I24 zz-~}BJ_D>Ti+%{vD8jU+!7WJmIr;YXan&7-UvAMFX^cL+T{F7v*lv`Ka~$Z;zJvhx zBbyOTx8RKgcgZXW5jE>j#-V#LB{ba}*}uww$0Mj!dsY47hNi67VFI~ZZFPMd;9n#p zmCWZIK6#0rRGiAyRxFWsD?YqI8az#v#5E0XJTzWVoO_|q4g-EKex4NVZDSXxcugAU zAHG?o0yg?p(@j6lNsXjuNwRXhSURh1=-bgYInZ=G&zFlED7PpODwlW2-^rXl&dwIH z2Ix~2gEy+-w`zB5UXJ`!+K2gG@j~Wa2grYJ07kR5$J!>vl}F|LZJ+5JfJeS@ zzeIbGmhwr)A8#@pXwN6;P{HUlxz18|%#dx~k93P1Y=})GN{2>IH-0f z9(Y_BpmH-0Iz!5by5Y)HpF$$BBOO_DjJq^Eb9uXjf!7lLDaH_5^ZaasYJBRYd%g0=!6Mscf1`1;V-apc&e9f zVtb#LmQiB1|C?$n7VVA33gyRo@%m7{Q)gz8;JlETPtUOieq1b&w+q-5DsH7V4?A|s zV3cVD1RJuFyl>-DFDA5`TMLPX=t_YxWW~9sKCaA8h^#56$m2oh6SWd{k|91Yj)${*QB@>xzQE_}BgRu=WO98W*&Y z#`_Ry9=P$L{$6%&)-fd7)DwHpRH?WCX<6c*TeXR1XcSy}e;jwGjqE*}n=bl{aejwY zAeE>C4E*fuY>X{~kWi=TY;a;)S0JbmwmB3!@3iQ;%q+lS#kr7sd{(LmE5i z#M{=&2(pf{BlSVXu78rLCaD-63_lZxH~VL!TebFp9|Rawq=AN*!53M@>(?WE*? zW89b!3quJ&ZRaO|nhs!pXzBt(+~5iFVF29sk|e-yVo8nY{7~i-T6Cy z*dnEPah09Iy`U|GVXYgcTs5iFVj$$Zbuz@1#^A{WZP@W;`fPH-$5z{va^dwK}(Mm z!)bsc`v|>9GsaN|FN8FZEHHCX_20>*pl>^s);O@w+0Du7x_XT%+hp2pIFR3oE9;0P zEs2>RsyNR9)g}axtGWTn97~}WgrcDOw-n1PPQ|EzE*Cj+__UafBMI$yK(R)J*s!wK zR6FU%*}V2PcXP-(`d7y2KE<=Ktx5lpXl8B4zkoua#E;P9UUGPAHC3;`c_r3lqWR9y zehZf3L{%e_g4r$y^N`qXi3UF#9SoA% zm`EgbljU#Vi8MHMe&iz7p$+u#yi~=jWvV1l<6Dw&B)lB^`nU1%hiRbkw9IXFpo?s% zUe!6wz`lwL?8fBEbqJ)A734n|3~yK}*6*sfn&?bKoT$Hb;f|%e`rFX7OtwzuNw_|P zLv$IGP!X%*6YIl$tR&CJ*+1zsuWRADKB~p_VzVuHpXvL1k{)P|AtvDJZ|qVYrX1@D zIT|y%MP`l<&}A!X6xkMIaKy*fLPr$A-JyCOFl(5ldEj5F3d4ahpW4JP?2vv_atg;= z2e~i4g8n`hr--1Oe_;594rvLSxCz z<2bISdCc(d;9Y0*B{yF#dTE3UnW66-#3R)Tz2RQb*v{$N6+go2C!pn>(6zIo^ybfJuy|buZ1JDC3Z!GK%KdpNFzxHP zMw|785~5iEP7=AsuN3bJy+(8+kaIbWr$fTo@JTpf2Dt(9qRSVjGm27~zO!l^jM-V6 z;YFq!zEOo6Xaep_Z$KI_6HB=xG5nC$H;aCf4V166p$hRqPgv5B(yXX{D>(3Sc9F(( zyOYT)NO4yThY7*SUP`DoX|pP>jb6w}(HzK82p!|0ul zXUJr59Sc|9%5Yp>i01myPFiN(mJ!8WqDo+qm3+U{u{-$^2$4~WUABmaVPDnkbhmGd z>?AjSjezZpbMMtO#=vp_l!jHq2pkb4%l%M#sznzZ$?!kg()Ubs%z)(PdlCXW-oP7n z0w2{<`Zz5gj4TbK$z(8+aR3@O6nsY5l-pMD5_PB|gyz1$ghak#@u__=Km3)5EM)D0 zX{Ylr)Wne0X5vI-%cI4ma;E zPxN}bsxbze1ay%!6NtNrV=##>Bqt9KV617>@G_<9!~houazA8o%+!v-*M#H%k`ARH z<1;dBQ>N&Ae4*>Ya4J~hc4{d+^aB+E;3I*l@MCxWFx-Wg<%~3UpNkA+cS{9k0tI5k zOBBa3JMX$dF_LOb;y6?WvUIlE)aO!mGQ@T;M;$@1#XiZNxw2dOzvn-7SaV!ILe%54UP)V zHAoUccWKv|@t#f@hj|r0jx!Cdvs74!SSb}FOc#SGWu>^Aaa)i$jFB#q0>*&$bpON) z=rV;7p@;8u;+hIINPXTGIWR@yr`XuN9fU?VR=gS%W(a*MXQjAV-ZdiK8U40982xQG z6#HL0{Qug$))TIi_|PBP#u;aC-WCjod2rr6_&5Ksbg>t%NG0%krSXrT6Q$aPKkf%k z)Hb45mmmr(myqUY0#yqGr9W~OgERoNp+goat-=6}3FN)d`dX8_;05jb8=7%K4(QQvd2kjybtsIBi`7JAC#tOoSx;s{|O) z7iM#dCo+0*I4eLgooVay4`{k=+MKtR*_$>bEamXa3{$;ZBC=yKvtx{u_Pi`<>dr-G z3(qm-ux1*++X2lAQAxFi?hWo{AUDL3$=3C91TJFCPU14;Z=-Y^<5%XeZ*0w6fSxJc zyQ6UPf-)(HbIm&0Slu75H)o5+$uK-PuxG8nJ(@&QgwxDb)Naq)iri~hSb#yQii$hs z8Kfe9(eOT<5&1jb{tLQ3K(;ga(KiP*vScWB?T?kl+pHC<)Y%Jg6j!J?ZyeOOmIZG% z1ZPI~l_puMBD@f-NF!wklyFeE%KD#_+-MZ1m z9fK&0MEncF6hVbQs4OqQsyGnfenxAy)@reCRQOD4n1(vgHO`a}WEx{7JD#D~+BQEIS^84;1HW0n{|Hs>_17?)t679YTl zrU6DP3qnc%AR0lhJe&neLyo^*d>CL6@_F(U1xT0}Pxt#))sX&CH7&9jG)QiFL58CG z?bM)-lw+q8WU2076gzYSfD)E7{j46h^Ux^v&L`Q9hsK?07q(nfgEUqS+59r<$p@Pj z%lS8-V0TPS4S3oNee~M4^t@)y&WN&rWwJbBjwWq2si+LujfK!s)bk5+e#!g_HK3)- zeU~eTNq?P`YWz!iBHLcC*nSdvn2#Vm5blj50V=oSOo~#+sX0-w8zreC>59)m51Uk@ z#n6&+Bf6YK;|4{mHRj2m4+@iX?3wN{W^j>df{h6Y4_UEokb&G~Ewu&=5fy?yn~B4{ z2xk`bi0+fAvI4aVJIcJZJeB=7iNrhVHjdQC_Nu%i93@>W@(}|>7ofS9{&iSf;^=aW z4QpOte72V92~)+BBpaJ^?Bupaq_qG zA4e^|i89L?g*gV2$ugVNJ~~FosUd1Ktc+|Ww93khHLC7CJtrO>{C&_ppi)`c1-;CD z#a`yAjC$rE>2Xbu3ljR&jyV-HnYO|D3?I zn;+i6Z;T}l6>@I6zF#Q+^`2_{EZTG}AH`l@d#*eY=crWqQvBR>Z*6aSz71YSrq;UX zUSC~ZUVqg+e7?=>%)sx=P$JxBKm0J+SvgK#412E`zjWKXv_FA=nqH;5V#Ho2oc-f` zcy@Wt@#I5haU&xOwVK^i)BUGIYcV^i_n@b_vpWDHHR9>{9kV)wj`dkOG7<{_7#X__ z;#x#qzX7i>vEb0?HC!fO@bBaIY&8W1u1g6@`pfr>z!19f7K)P!1`}5d9n=;$CM-to z1vU1So!#!v&O0FNN^D}~6`&{LQqlhb-t@sVl;MbA6g%0ICFB)yazogbSInvmM3(kL z*d{_Ko#xxRr*DHvK*+x%rnq)um_aoRoz=A^J_4Or=pOD(aq(KY`Es!T8o(&M*jZnW zFSqM2kK6sh{?3QPLZ+L?Kv%c->*>3B}IRR_7|o)K-+?-i=UCA zyv*i?j3*-S?y^gtKBd*ruf{kJhKj`p^q=?+-$vDDI!uu6+068gmb;Q^V=G7mDPfKXPODk)d?!aChqvq+|^fWf0SRj@#USB75(+JcESvw zykzUf7rwjW$Ma291>P*oO`lVmua6KDq*J(K7Fu?AMp`+yW5K*31tjflkdK{Cr8q2K zu6OxvvlRQB7kz~0j+EaV7C{wz#A#l|#?Au%6cvR3O* zHN@$Db3FgleFEDzG@HnhUCh9UeZv)WHCxzF z1Ye0f*tbCn)aM$52>jY6b+JEV$PFf z`<-0II`bndo2yGGsp6oRE(7bpn-jy@)kS#I9V5&Q(i8E*_wIiqj2tH21LwgEY==Rk zGq_leNE)FS6-5#$>%||VK!lS25jP79852<6a~>m`skByV%g0!L4X8%vx(=>sFrLcT zU#X}ylpXbQ_rgzZ`+H%C@X~X6<5|cR2QPw)4EBDtP3TMtoVe1gAxNp|t<`aosDA~< z^B~;wTa} z@BdxUzd?>aX0U*VOHK^+%pGe=CUpBt?gV?!i)bcS{=FxEig(gYG}{L9c#B|$d*Dqp z?aubyzhC22^b#&8)-nwq+LvIzL-sy}Jp~Wv_)NG%wV=K3j)!+WA?lG!?vw=K_7{R0 z^R!|GVM)qJ&7R)T92$WqQMVH(F4JW_?PVR(tL@+z(ezx#e90}!^ zj&sF}5|osXosq05(3pr@IGmu{RSc@A=;Omj*F9F!&MG@!@G>ytt+ zvN`wh-Lx&E6Mu>8$z#R=L;1J9c7p&qRU@!bor!k0en>}IReICsFb;zRDv$E0It*c6 zC*HI@)m6-Xg(pK^*}p*9si;xoJf^y7PIYzKrs^=1`0Q-ToFwbDNtT{IE#%Y-D58>?Yu&pLEJz2OCaNe3cIaLxo5qksUZ_{R@$v!TvvNz#>obQI@%yy zyH?gu4#a)+wVNsmC$xaz3tElOx3iD@&Xx~D>2p}SiJ|a{B3mqI{=NT$poClc2w2MJ zi(|bX>Q2^C?bHdPl8=V)wqm%C4+yW5M=l0tSz>qPzg4fHn-ESqXm!%pG!6p?FXP{_ zETpepsTw8={-3ev%YMf?e**o`-R3_%!fB@i zvo)q2&h?@1cNB1EN1_ivhv|)t+~O%6pYQef=QC<-J$f%^#S|0UU1{!7pWc}GLBFi^ zTqNF?$p#7zCR$Xr<|Dm(JGOgfY5bU(neNEE7ZRN3;z_-jC~3PugTJ6A0{X=_*Xk_p*&P*wlrlFq^?X)J@yBkYY< z`VmGItO3(V!z)&WiR|a?Lp~vaUt=2=UF$m18s(YuGn$eJYS7{R!f5I0xiLwwevUss zzn*J)wX`KC-x`3a&`h%7T9sIrx8~mtJZ$WK69RC*Q*W!&M=0X=ELxU}YkWOF6j|gh zIr;V^@gp#~Wj3P~rE;a6C;|m1EN+lq0q#y@pE#rjRd?g31XrPxYLG>b@@J*V);cCq z6w*12QAOXqO)0H<|8Ic3`|E{$1_%am5JxS$OwUABF{kNEVto<7k3=p5iVj2nxejhD zc81TkQFiVEkWC7>J?s!L=7@~Hn>ERv@vNwihs{71Iqi>fZAoF6AC7G}b)6iJBL>)^ zPY{(lsDg{}i7qC-6DL&kiiP!cRblIPuD2&zc@ zOz#w%zq`|H*gcU)#WlxXS+sB)YoqZPgV1e#rta&;xAZ*(fw+5Ee0MTjPZ}Alz)@TD z1#+p@HwWiBkeq55Zr^SA42wVVzj#JkLLK?>Mggm~U;_~tCh6!O5HJcxlRVVs7T5@q zTÐWnD6R!zvmyq`?~s`R;bSmY$mbe6C(9_y z4S}RErCJSfh0wVm2D}PqM#nY`MbGdd($~vhNE(=CJF5O)u&a-QXl51}CI6nR2Elxm z+VI;M(54`p&>Zi&8lG=#rCCw9Hh@axW8{6H78hXa0sL^s>XJkIJ91F32!A&Er3irt zn&c88f4B&)19TJ7D@XAFVjaiOt==DV;FbOlBMD_3VjzVzm(HPKq1Z{T6-0&yP$^G~ z1-T;Dclf4b4)2)Sg9bsg1)m*y+Hx)hJ8d`iLO@{@)C|PT6&=pKKIGQ zl!O*;^+~;2p$X9FinvsutG>AZ0BXAKm{H)wu-DHu1rWKc@O9=Z+3RTxQvj{gc zNY4j+yMWHfx(B!Jf5<_noM2L%9S3Kt;e;+M4}G&*__f|Il@m7?PN6#NHs7nY&}}AtkL*w< zrzbCNk1lN%ZB@ypbyH7CgelTjY~FRupL(-$vM+cfX5d-vB{Wp;eLld^)66@_-bB}~ z2_G%e4JToUCtu&3zP!vz*hBNctVk@!aR23o^)#DPdvxb7SCua9pN{-U@Zqb36`gB-kNT_vKehf?Pwoq-3t z75$m%gp(hGCy_(xI?0piJQA|sFt9{PD@dcv;gFdB-DSTfzDfI2`Y=5=JS}ACz5{N* z_n2wkzoz*;z@=S)Yt}R-l1f3Ye{S0&?MH4FEKJ&ww{2?kNVl@J+MAg!kFd5v%brJ5Zl?Sp_=0u&wF)t;%9-we6<^t!1X*#xhHL}l{^|8b$5 z1?&<%d8XCbpITF&Z@5CT;)K%a0!E>c)*-IQH|yr@>^@0=4?g}WI6-;*8AZt8HWj-a z-{^}OelfpJhZ#FX<%L_cx3NQ9PfZfzl07rKbSGo13ej-bd^rWyM7L%jr?=ZPon?QzZ**qXJ7MkK~ zsa`b5u;Wb0yZTL{^D{<bcR;T5DV?Hh$;2j*o!BU-THf5*oW)dc*%2NORw+BP_;`5 zE#=NcN`f6}Dl>90rM?(Cu7KiIIMN!v4ul&e%0|yEN(Y^QQiS%~8`8K* z$HkUoCm8%k!o3FVUAr7HvWHm{h+s8= z4Mwr7lZz01&Ml$QTS+kt3rAU$Nk6p!%PVd9LOOT$T&y1~7{&^s?LLj~F#Z<)5T)=@ z);_zlHtxc|fdPyvfS_OuIUTJ$_a*BZvAvHLU-Th&@Qu~K-1D{=BlXmnr51bciw@1- zP>Q-JG=UjrXMD1!o@N#&E44^%`sy_sLD?=guhwKq%?2@H%l;3VOo&~m&3Ek^P_A<3 zk5x|}!c3E{uF7mL&Yu5n9WkAR(sy7Hr+z}pG9$IHEw;v5f#*52D|gX9rM8E-gSi7Z zHJ_yPp~4{9@aBL3-pXT0EtCqgqcj>y1WTQ;G6EF|fG6Q!G5djrXaNy$xV!JQXWh$7 zb!9fJ6kZrk?mvi>ek>0-lkdtTAN^sX1$cW>%f<>z0VR^Pj32%5NaaROFD58&0lQ7F z_F87#pNvs3S+#XN)qHiN)j|JJhAbLVGYAN7J*OI~(28Iu!l^%>HasH~X)n zRa%UV^G9)1&C|-8(#_LDe>MIyzxBzcbn6cdlSGNy>n8O~iQmU69M_2d*V&i>fjr3t zbvRq2 zpH8RoUAllbv1}TvmemR`O+zVHV#?@FSq(5FMaNhY!5Us*(8SU)!nKt=a-!Q=m8BAg zr5fE*o#Q=Drc(BFaNgI4`}^->$;0B^{CH+#jJUyLYhYrmn3+RLYT!PuBnHJpNYc!~ zEHfP`_tLzf%L4yP>{rtqVK|( zx1{6p7XQwhp!?sv{H^sHXnJ}w)M#H$QqyCsOJ=e4v7&(sktR(AH}85=(>KK_G|SNt z+GzG3=Dx93>IJWiW)6?plQZQ#M4On{?(^}i;W z@+#QZr}SE?XBki)grNqMV`Sz9;*C@cV*H%6bcWLrhZNTE=6a(QJk&x15-JBA@+*<3 zB4+#MBNz4o<9S$M9#YR}bxkabwWz0lBp>e`VT2 zC{_GNF**={>Ve$b2>LdM5onmiUt52ibGJ``_j0!axg1ub^Z4ZKaL2vxqyZd0e!U+8 zrE-E6#S!|Z9})4+Dd~+{%$kBhYh`o}h$;2toJ8gZsJA;>p~-b~*smXsej{@WUGF7b zCpY+=&ORP)hC^)Lv^DuGyCr9UO&Il_@ikcQ{F}QQsOBT4J5e34eVLK*#2LN?8qUyO z?P6O>1)H&%Pzjq+*Jf-fWD1$lnDY8k|Li1<5i8Ey(lE5JD*th`>#Zz~^MgY$%;iAd=SlGZVi}A(opP5Be;(mmW z(7ot$-4QzZ&2vW0o3>`*T03GVm z5EikyUm}&Wxu@4&`Ohqo&N9m2dE-}FUm4$-hcnobz7DJNf~}Pr{77dV4W+fBV9~Ih zOox9^SQ7^+jCS$hXql0AQ0;XX?PLwzuT`TN>Ao0r_7R|=Kb+`RY{ZqrrfAhx)L-A&1v^g-X}$S+_LTa( z-$qYnp#Nc(9>)T~?qMl`vvpgtMF8c4$W4ovP}X0;^oRkCJ9V(bs#K`yMC7cMwi(FdTfBgK+qijuXm;G+SD8ez<>%}bYV)d{znD8hDjm^7x$Q<^j%#EP{uY6^^+P=}>|dQ_0uD+`iqp{NPoinR-hHs=;s#V6F*bv!XB zP4k*O2}q3gL>1SSfTmlDWTiJwxQ%2p94pW!lEfY{qD?wX+E)}iXfOLtz!)D@Ym9W1 z<*zBxgdbzgE9t@=S6nHk44~aJY)7;e5KSJXb77s>(0?Hk*jLClE7v5Bluikl z$}b@4@Nk?wnv+Jx9xA)L_5j`iP~-kBzNIqbm&b!Cnh#uwq{1+N=Fg)D@H2%3AaW6q z|M(XliF7`QrVLe^MmJN61VttGChr#o76@M#^QfU+6uV`PX}}OQauO3sVO}Xn=!6}r z7Us%uv>9ZM{_S`=X#)_o4}~ERL_;t%+?R{>(9m8UbAq^{@c40^tZ5zl5!zU@KkkUnZ6@=!PH+m;&@N5exv*2dWJj&CXgqij~!Aj_j%@Z1x zS^rZkmS?#Lc=^7UQY@R!@%IWlxPd}=3w>AoVa47@F;q-F_=q2{Q+e7g+{8Za1FC9a1YtZ4(A1RKL|?b0>-KIBPCakh zFLZ+Onh=?0wr-qMa|(7J`j%RX21(Pqc0}8M{(l7T;rG;spNH<#S-sD?kAvgN>{L%r zu1-(BOKx8{#(i+R{~zJ|xIPHv1FxLmb$Wy8h8}O5WPaKCL^2qB4R{javZNM1y%oN5XK#DqfWdvrT0U`f_NQBY;-+XU= zHGqtj{&ZKbmD_KJzb;-YKp4Gvxjzo?cUvD%dxN2YuBW47W;^HLH@A=5nTHRDi>|k; zay$KCN!$zCFqZ`zb^8Oli64nKsY69k}}WiOzO@prW= zLwUhMRxl`~T++>IZL?CC8Lx_uTIzUf<)%?dEhu=i3#n=7wBqf#RX7F4<7fKzEuYnR z@?7HAiJE+eevzLdOxOcS%}TyN-Ci{K}u1 za&R=sPl%g)xS!La`Ssd93l!(->_X_1@>2}CnK%53SV{b$q8|#ZrB8dUZ$s?6butc4 zUoZ~L0bv9fJDj8xQ6fffBi1fOIi$O7^dn&^%;Xj&?(7ymiAF0R>Qb29T{6f1eg-&v z(2|m<4##qb0H8Y}$AoeR1uoRB77#C!D}SLo(}UFutxil^l5pO27MC-IE+o`?kN6GG z1)nf5^cGYdOasDa&t_^t6u%ro#0Gtq>?$MKEB#lfiwh~Yuh8`>d`dsIVuJ0revhy< z`l$aLGx|p|VyS97NNq5B@;~P+2<{x)Hp>#O^l941CB%bZ42Kut!uC2vz!{!f* z*jcvmSaTCfZTyZ#q5i2K+C54kYIaNy24Be|+XKOvj+0kFsPIp`j-#R8U>mNZc=uYi z0bKPrd+z+=AP!j!((J;vK7PKWnzgF^(-hhD;-;oxR8o-Yc0;$t%a;XOr!L`op}3~j zO9->na=)}&W5`yTc4r`VPPA^*pJ>1M7iQZy$r(e?xqgVb#j8GgIT`SZQP?A#FaS! zFZm{Q`5PbaA5mKB8x_GI;PGk~T%F4MLE9Ohd>0jMxaoi5$O_C<#9UXhlf&(>*4b}y zJvybUX$68Zh}E!(;evVmOwo&zNO-4{Da-tzO$mOCvZW8Acmbb!IzB9{C>$9Zd}wCY zpOFf`hVn(&W>ipXnMq36>X;tcrEm*9n(rn&k@lShHr)GQ_bHKRD6EU_a>B+rfIe~B zP@hGS{e}UTo#W;(3K?F&#s;U9dt9@B8^c8QCVN``R_L|bPGaVQ9E$sfVF~Y8`?*)*%JvZd7``DiUW8Hoine!uTygG>4=AB0-i>Okrt&wIHY0bRg_+YhXIqc0+v#@2Oy7QDC1@7#m$_}Pw5s>* ztNrh)Omlj9*f&<1-#dV#HWtn2N{OqMX!MJwd64F8+Qnaa#2Ahi2s*Wu>l@@ds;g=e zODe28lAUMqFv_nqP4rG?-f~tuEr8NodtRm}mF)=z@>MggDKJ2L@{&$xzPbaPL#!IM zua?rZ)RL_f9!oH_@vN|vQ?nFxGkg^uP$JeDszf@!Dlg2VrdRbNeF61Xp^2b?2C2cI z`n&M7aCMXPFbLyAB>B1dDdI9CfZurCL~wglNcMgjuSr%A(kAJ#FjHe>hT|;E<3?6? zDm@GiOS$POLSVITlX5csEb}7dz-pgc`NzL<%+F{1e|~2QB(Fhg1j5RA{>@t;4{yt~ z_d0To&P^q4xGQY#^kC!>b-Vl8Q_o_*ZKK;lEvta+&xnn<&}-8#8*wyKJ+t%N0$pe; z*+qT6uHge=!$herYS`a=f6d(L$HC23$!WhL_sEcP(>YJHvv9Vfzz8ge^>cw#Gp9Ir z=P-zXt^2Z)_;WpB-w9fRXSE~^7~C!oomTX>v4OSZo1Hiszm4Dv&fikR>)qpe$xPSC ziYHAepcbIb)IGjb!3DI;^~d4&q)0l%f~ttWEl`SD=jv64;}~ns31^!Mkj-MFt5uRL zzUuOgnIZV_uvAhs6c6hN3>S+5C@*D=QGhD0)ry_LP{RinNf4?7xLtoxgR z)imi&D4lJNQmVt6;u&YbbL$NE;Jhq=%?k%Nu`n3F%Yzkk`u{jEb%s6!@p9nwYq=NgdL@A&KbyW8j0;W*j;+qI_qyCb2r`&)DSTYK+Q*Jmn| zW(Se((4=7tH0N}U>Qab{2ys0=#n-<1;)rUf2rcxGjSKLR3I}^k@4>QiE{bc!@DhFN z*K?K-QlGe76CC!XsIvG=qh=)<%hy>pndbvYXY?dFBgq#_!5Z_1kM=Hsn+9sShHNb}P!$iNJ!p-*@ zp?mso^6EFn4|&x(d%fBFCkCzPq`p@VKVbbHOAcr6Ys;AqJ0#GX*zG&+v(HDS;a0f) z8busF*ss5%rssAhjTfmI!zL1m3RSC*pVbrixfuO*uHl}iqT$hiMsOWar5lZ!yFn{H zB}d&xQZlyHTWSl$oPE)aL<6fp)@Kv{2D$m5a#%4RH5G(%OL(dV_c*fx;O|wZQk%xd z^m~s`RH{yPOW5sMF<{tL!h~Jq3V_i@nny%S*ea}uz4azdDSVu^e1@)j))%6^54c*F zwA8Z3D~`ODnxWlm1!C|F=A5%yyShgtYs*82PT8O1ajCUD{%modaTwI~03O`Bm9FiM zsgE=}`n&+)D&oi_%}%YT z^!BQnOTmyEhoeEW@#ixM_3CP0`JC_mR*~}VKRPTn1H%;COwGmnX7`a}Ds)LkDE_VU z;bGiF-wuN9Kl+(eDJfM2`(q!iHc5v`a$Dl~iY^FDDOQXqDC91AY?ua$yX+m88GZgi zh02e{y?Ilc&wqRJ8xxMt`&IfUCY)dO*KD;hA#k}9MoCzLgHC^#7GFo+vJb<`8~V&- zvtdNEE7_TgH88v=$MR-;GL~S%OjdtDtCKx(Ks_CZ6nmDRMrJnjKIt10;_ILk^O2Qq zsWo?`n1r|pVWbc@3ApQzg9)VQ2~ghdB*b(f40bNWm*0nfppvBN{IiIG?jVH;!~seM z)7g?cP}2;EC($1-E(Y~@fg$5E>zew+W{RoBVd7Opfz73{hyfF7S=}ug|5{@#gE#7& zFzlxq!e@>t(N`QL+%?dpsYqax%&L0rOS&D00}h_F~O$?mtDEwSgM6Ab6BeKgF7$LL=WwCgo&d3W{ryw_VHDKW&y{0$Hg(h|NyZ%gS4 zlDPCsva5IGuv_0=@>l5=F}dufSeHe9Z=2^|>#DEAv~flT>n!C8BbCkN&lO&^jU1=D zN-=0KJJa0$)ji=&nqg-a3T+=V8a#`0rrTvD-XjMFR6MaEHz1VmYf#XZ~)A?LZJG*Jy7V za4OSFXQb|%x`uFx8}^0F)=q+rIH$lu*Ta0bG_#JF)7UM}R>lKN!muD|O3=CTE}@Vk z^CI^dEwOKyF;XeRejrqZF*{G=2QUZSei`XU)00p^cRdUinc31H^Gv&e zWVZ97l!~}fPb`2QlCU^@u5z#ka{sNs^@pTFwuDQPm!ps-I!>qOaq!r@n|0TZ>lGkX z*p=?UwVBEKxu?x!Bz-L2B~W&+6({ss@sP~!4V+UnPeSp%Fkul}+636*G`a}Y_f6qr z>liQRby{6&R6Lkd^LIcL*60rnuU!%g-+g3&5XlmAJ*3~u1vNjMPJA-#mxPL}?za4* zqLIdFI+jmjBxg4=B>Z{`s}WOhwBB*@@{>l(<*d3A1m$y4(wLwd#r6psW_Aj zR>OWl;kl-}Jbp=;=1S6;l)5omYoe1I-e?4UpELiY)YeG4xk#CS0V+g?jF}zETgRLl zlAqK*>;@jr1!oK?4;ulg8%7;bU?=z0a7H{i`Zdqf^C1i;OS8g`d67ZwgDp@OOnuaP z7Jjy+kVPytv*91|%AS?=seXuebU|pvG;0U+d4IZL1b2w^gWCl%EjDqn48s3r zv9q5P^pI!9;w5AN7Sq?`%+nag?}lVn** z*$P!02I-{))#)*e72T@vs!W{-z|v6Vmn^=o8ib?v^bb%oR|YcroWfcuuvR&S2mz+4 zjNLbLLjz{6@OPY1qKK05M@KKa{BWmg>EDR%Ulf0xG$&^3O3>CP4G_ zP~1`yF97Cn&8)cD*mg)cP8=~8r=KETjP!YEZY19no`KZd#AKS@QYk!dAe6|zqzFmY z@YxkcmhEB!F9+M7ttiwM=Aq(l-1p2)7O7Q4KN6y)>}dc@3~IsBRlWy3nZA^=VNsMQ z-me%z2Ic1&FAG*YiJzyn;BlRj1vC1bRpA^j5DwE;A!h)bB}lHEmCrt}L0&CFo=(hF zEccIY$v2W)gBBPSu70LTvJ&gw78;FA689S9n?=il88<@2)AecUF=LL_t6-6IY;Mxh zh}L2#cavx{0<@!b5GQNI7)%IMxz?s!mGhzvA4Bs13GH(C$}29leIOLUguP$BzXE+8 z^FY1R-QvJ`_Q=Pkc8D?{gt>h}z=soY3e?ZTfTAujvz?%J@CU{*)RujO#n8lcYfzgv zhXo`vSQ&Jp{-x^lMaDSQDC#S*{?7iGC}x=g%$vw?t$ksx=1so%%Y+g~PMzv*)y<0q zH&;5{?|{3st;EI6foe^fD7&QBKOD;RehsI`Y4&i(k0Lk?YOE`a@i+Y>{_>ca$Cl$D zgGcV7;8^xyzb^cj6kFCH6Az8x7~d9wtivJO2Ul-Mt&LlBszRBl`7VGJ3b5byK_J#?f_w-NAnk(@ zRVLV!3H-efgK!4^z+6=UDV~{v8XAg<97#VGdMu>^`@LL9a2x9as3DKed#Bs} z&G2W=PR`uDRdVKoe<~xE?xa{tAS)_^P>?vAepZ!I*)k9FAqyCn*JK4UL=EadXBSBx z*K^|myP-<43g-`&g6OJnl>Q$qC9Uzlv6Oj=A1ozPgOW9=E(=r^igH4y9Jk|m zuB2oXQr=Ozj~SAq#0aD567fZt)IU9KNIml)GWT>}B6$utQW<@|ITqHs<#I0)xzn8S5eF&7pXH~s&mm&D7|_WA!lc7ELBxyXLsV(Zv= z1NLcnn&6E3-#3lGL#4+B#y8^W6lQ(T-F=~wQk*IMFR)7M#t*ClTz9c5KUUFD=RsJ8 zuCLwAFO=L>#>B7E`wTd^%^vm=P%+~V32A6z`ta(h6F2L3+cs4{`@asJ`QO=jxIA24 z8bN_eNby2}rK%!1WP<>u(Oe54fh^hrcT&y>wMaUD!9?w_gwv_wS45?*TE_(e6yxcq zXGPkV;7dlqRvL=Y#zCI_|Ew7)Bb0uzPTG0Vk5en=?mtgY6Xa3?ixW++gAc}?uykV{ zCOlIuD^q0Amy5S4U?Q1Bm9*prUi|u*IcwNTLAI+Ky4&ve;U8eqLjy7%=aSwytc(Cr zUSwauT0Vs3-oB@}`mjPSuT1m29=+Do)1>^?`{1SwGj@k_W?Ap3lCeSVSUd5+wat)g z3|R%CWtP3a`UhkX-?IT$-(w8r;a?gSjiMle6z+Q+KP+>+;$?p%H%Cn$fu$4saklZn z?A;}z*yr-D>-lJiUc~LMMT?kn`YT&{0vD^$g)tYlMQk}xYpYCFQ+^DhQE_zN<}eU0 zL(Nh0%5m=UpM2NoEWCYlb63uMi;>=395wBI*XDRG|Co_GJ#Iag7k+AO-o7bwG`?#d zzu)J+UsVs7WB2(fy8#;6r2|`Pfr55h3?uS>UWA9Wn(oCzDXLzghnDFw8v%#G+imIc z+y?@GIq0c$bd%>fPzWx(`|5c=em4bnnvmAC4~!!~=v9G0V7XgZlW$R3*cjx#NS3}- zG!~Qp(tJ}u44|1xau16270Cy4jT&-WJ(mD%L~fU(Y(+7F_}y6P7mhHM13(-{B~d^b z3uX)x@;63uP{H?Cy1dZu_i(s1GV2^4i^Ig{RrRE8cggQ={X;1C&LK=RK5&dJ$=fpX!iVi6pE?R@!C_Xq2>CjOXNY?FBxwVTlQ-w zWIg2DiCTL6|e+R*5~TZgkzF!fp&>*9Ef-l~j4Q6IYvn zhw%mJh7+)c)Xk_3YVXl>y4mu%yDjWbr<>b@&Y!wIuZOEn$B(O0MWiY07-ae0Q7fmv zA)G4K|A6 z)ztQSh{`LD(C^J@fp54fEz4BE4pPML>$$xiL#KO?_rCyfA@SenMnS zzlm8d+LAT~XF5rtqZP61NOX4?&fY~WC}5^Ns>J7n6M}L_i7A$fDb+RJ`$2(T&#*-y zgbnp5RqVirN_iuQ%;2Hl9im-DRx4Bud0V1*DPmx_HUy#6ik-?`&VF*+vQ9z-=~;7i zys?j>W6zW5`#juo>dBNX`Ip{vy^KyqF!$KR07d}KKqwQ!JxcUBM^|7XRxZ9g+@G%p zWx&8^UR<1r!!x_Hq4)c_F>w5)mz3=BJz(NOQ~W0|pBXTDX|=NociAf=Pcr3h>l=of zl`qILL=czSvB?i4&9;Zie;xS&I@qnqU%Ib%`7co*49_TR$7ANT4vK-jnm*Tb-logEpxb1$_Zy~ZbE^=$8@;wLaWDNW%78I{N;yVlYUc)Y6dk)xq2@ zbRI0~5#~i`HvX4;ZsTp7W=60jGQoRpTgTh{5Dqy2b?n#c$Ll@Mwt+%NnbWii0sIQi zNclto9uPjTwN^suGHvJhmnLEd-%kpj(=`^?@alz=cCbg`8gqOCu5^>A@`Ca1t)r1) ze@y7Ak@AXN6Gu0NI-Gz5oDV9-ls^F(xnh+GQ)HGTd?eyVa%R+Eo!!_}xHbxhfT8Og zjX=_6pPdx$q09CP1S;KHG$*>@Xp63&F}-#^);7RQ4IT(~g5Gs@*w7l4!5d2|(D-;b zj75`$&8UX(DB@LheFzXcW66w(DZY@ZfYYe@m=R+1M~tJ; zBO++1e#kVRuR^XqAb$k{8bZnQ1Pj3I@08_b#kiA4RTH%%`N6UDT#MHv$eBq>RRlYu*oug#7_Ax%x^?S@>LJI> zOufi08GPe%W>`u-GEndme){-m^PR&XSISCfdo&LC-ap(2Ce-zp$E6TarfK9umX#mtwZ7YtB*-9) z_`rrKiTNm&f|16ox=#;G{3%T+Vntdqi5er1k^y00I&QEM^ppIb$o1@v8TO{qz4A7Y zrOLB9DNYuzYyuZRdxl1-Tk@#pC#WfTXeWE+r~Qe?nE4>)i-u~{bqrw@@>mhH6w@qp z1N+pLv2GE-5|)kd#-!t;Q)>MN-@*90yb*Px!TA;Z@E=?JlVbRGa;qO$#yt964~rm; z@iVxC5$L%pDZu7~%sglBG-hbwVruL4^Ut~W^v2iHhD#S!n5d(bo*3w=i!B+oFFFmU z2vLzkZdkS|pDz!{<`(k+URET zpm@Z67(x2RsK`*s5Buya;vf7ZirxZ@*p29RZ#_Tl5Wih4;J}8a&?^p8#C?~9+HI+1 zov!#SA=zwzM8p!eTgEUHgBA;WNzv;OsJ)1%sdyTeq&wS}QgL$qELTRlliJ$`<>e3+ zQZbc+79OVsog_}VH7ky|!LMAxqMSCs2vrw_BVo~H=7NxJ$b`d}CB`}@`jtO&PK@g^g@T-t>f zdbCLI({f&$b`ZVg9b=zSDgZ$cj=MfJ(+;a!r z@Sj59uQM3Zt+qI+>4V`$7WWy2_D`&Dr;TrKO%U+DmOUb`&DxU(;xTdDJ)npC6Mvgj z7@!Bkh$&`sMKvvKtTHi2Q)>32Bs_&7;(GE8FJC_Ecc9?H5YAQn2?VzLdP%4&4Zt=* zBX|vcMG_Z7S)dy_IWdVC^K7waoFc!^Xzy$3G!a!nQbIof+gUI}GA(Kqs@JIrBjW2j zH*h{i!qz_r%;J)J{49HtN9d6XjJ7B|0)lrLGB6N3by8v!uA2vib!ok=Lq{TsRDt%# zDB02+D>L@$%4kT_eQ}ZSCs~@WMw9Mr_0$N7xq?j&w&ajZ_~yr3LjvuNiBo26a-{W> zQb+i6mH(_%y%MrLf6YS|z09;~1Pm0%%_h)NTXn zV{YukBk@`K7!)*-?4LO1y9x~*v_hdsqbd|y^EGiJ!kAv$mQ5!RY*^XVXwpdDiOUTU zI)TL#>HW>lf-$5|F7>Z1(B}n`4;p3`XMvy%{>2ADY>5<%sXVG>m2oz~*qw2Z$edaf zH&A3WVr4~v)_|BKbaCfaBJj1xq;$7<`>ERBt&DK{>S?{j2S$+iEyQ*=4(V~w_ML&> z1o%WBj@LliCdqR0tVpv>0Usc##PphomGa|<5On_JV+*txHbhmE;F}0jrCKU8#jMe) z+U)1!;F3^JkMV%jY!#QzR^H@jg{v3W(f`y!$kmZ+qyGO6` z3T=Z8^hx_5H>}z=6(ZDj>m#$Bdt%s#%Gis9x!&eNVP+>qO2gmc((8Ir-^ia=o2@s` zfSm*@{39Y+$hnDAyUPdsE3gdDDF0HcCoQVoP1haklc}qmj|WP9BbwrqIMH7nnr^ft z`iVLxjpcLs%*6cO_wp+7M-IyObK848A#8Wnx=2YiTsaavXL^{-4iGn2e{`=St(K@F z*laZ9<>=BJi?Pi01$Q-}us4d|xwB?B*pf>#R1oqF6aSl*hv&#B zs(G)1BE}0L^#%7=i3i*bxANOEPvDwqtx~Q(1yWAHaxXz1>LDv%^VJQ~4wuN^!GnSg zFsoT~C}bKZbNHi(S@P@IbvpgfvJ+dn0|Fczw~f}8En5WAFDZGxr7t`4KYY=2w(R2j zf8Vw9A`K{M2L&UrDn8-o*sdqx^e59#f6Ot+LTEHW5V!18Csxoz3f&=IC~i!!=5Vem zXT}OK34n>`b^xR{a>V<6?CC-koBSVBUZhgEUM)IEsX#Zs1~hYmo(JV(EWX8YBI`Zy z#@yqHLl>|o4&Do0Eu-c1hdWy1Cm=|bTmPQBaL_f;ojSFr)xjhU{z3`if{O*kKw{k~ z;bHV!06S3sWU>ZFRCl%ZRGT>ClG&H{<$qr1K`dGfDyQ0W!OCSfSx(U_qiFfey_s&g zS)RZ5l6Dk~sjjxK*XroDSYBq()=GG?Ad1s|Z}(>nM=!>B#@x97#%GT-K}>7N@eMt?L%TVztXU6? zAg8kcEw)xZr*!P34*&!k_1s>!vlZ!Fzrr&S?&>JF2mtdpC6`pUBwl0n8hCU0v$q=W zgb1EhF~OUKTqgfL<|=}tX=!zUZo^8w4}-Il=1NrN2zvt%^Pt*HTiF$kYK67Ak z!*e)=Re5zkpy9z|%wa+<*gzZc?+j8>sTrNQ4 z#nTiNn}6x8Vh`=UctS~mr5~ssPdIt$) zQgI`P5Dm;5k&cPNCSWhr+F%cpX~n%$T~<^99OTf^qzQ{d^n-u9&%#+Km6L|Zo`|%R z-@i))_>n#_|3~`NsK~A4A|l?JTmx4e^&8nj(5=l0Gs%@cSvkl*vdeAR_wu^C)|?eK z8?0F~UL%E$BXX?orL$ME9M$!Ar+EbG;|Vi(9eNRSt#T__wZ3EG*r&A(sxt_raq{^M zArkSd=yt#fH4`9d4Od*UwVI|`s2vNqz-1j%#|K_;FU4hkn`?b&BqSl$mLD+yFLrWJ z3b3EaP1C`wnO92MTr_v1X94%n;c6USumpv8+n#@@NUsGfTao!JRQ*6QCHW!vnim_Y zzJ@*bhs|>j2r_e-PVmqsj~EuJlUpWYm^5QW2zL?+$*Y7sW|20kr3WsQ`G^sa_jLeK zRYjN!qp}%&AL6!9I{f!iR`Lb^Ha=jv0E`dH9t$htlN3H^_e23<3NtIRXV6O3UrQJK zmGnrXl_T9~X=92>Wu`rubT}Nr9gdJ}_G&9N*k6wc5mCngNezX8x8!@ow>Ac3`;uOx zb@CC02HbBie}ZnOjF@vi3cYO^ZJSmNC_4u=WBTZ0kSdGru)Nn5UdKieBXUw1HIs@1 zRx9oj^BNN#9eV9=qXuz++$gFYQ89XPC30$iBY1NqKWiVdbJscTpO<3moxnEDI%Gw#E4Uf{tmP4$}{uQ06%ZIDf4zdS6S82786U z>R;1!1731UEo3aZ(8*uTi=S$Nu3KOJ^g&v`WomAuc7o>a`W{N!Vd-Q6zJ`o;&rkOtFr1pN8?OILXtKau-MHsxT#1K4s5naHpdlr6zw@ zBB1UB{C2awB6BFRIx?$_X!n&2oA=N#Xx1wH*M4?8^oD`B{@i7nYT(2RWuI@&(SR1N zc4&Xd5}p8^NNSsYl4$S*8Q>V8m-DuGuRiTe_x~(>id0DXe-}QLGyHFbPfYy(58)HV zUNYXjv}iMh6~X5%zSPm8j3ZyUCbHwjK0TcjZGodsegPp4xkZI0)fr`-pnA4K*;(2S zWEHT4ann+C^r*$94rr4~CaADhCq(@YF=j~buaPhvRQFvSttA&KhqXf_0XAIlLDaEy zH5FXMVQn3da`ZWvG75nG4;$nZXnzi__i3cqo~fw|Ar$`ngI_ZwSd7E60r(y8%4tts zUqefFu26*}Z~SxHYmViFYo4?kZ>+vIS#wIBj?c<%hm7vB62{{r<&iY~xEUttTVs)d zs{yB00#&enMQJ>GfaCU{o^H+P+wDq;M-b#8JZfmQF)?^Ltsh9?g?)Hck%vE{*SlgG zR2|*F{RG4BACROHUYgB9ua#TWUFVM@P77nGm52m$dZA2=@|~&unML+egtWEp;Px}J z818K&kt2Gq;~NnO1>`UdQCE}^T#LNlkAKYx`)T|-yfS`Ln*xz{nvwH&TN3WB(*m&H zP2y{iW%BwAfYS;srnBEkwKRL|L+IK+P|$N#@|FA5X@`q1xWWdYivrjBz^~d$TMWs4 ztrO~fj;3yF6K9LhJ7{YOgU=M~@3+k@0T-PiH>K0{qG7198e0COfg&=2Bwd?v>D*xw z^LtEbZ^`y4236B@U&7V5)xIf08o_^hr>QSt9RZ(#K(=$qzmFsbC^`bozk*BcAXZ88 zQ`{g{14iEv@2ZAxif~HyNQ^?|k~5XNgQ~RAjm9?}a1_VmpSz$Bo^*Z$oNDu_HIeo!>{(}wHd|wtL-INeFJLj7e=(H3;Le)<>l^c z!5b*xM@QiRkgj(=?ITRr=s*_|2ZOPS+{cr#+-k4GQY3WPd7icC8W>rKl`s0hLeF!Y z#zpON_5&iwp4i>kU364$(=>Nz`R5i8q)#??LITd^fN@0!@U#csK0Te-d|GUTOC27| zHX>yEjZG=Do5ugRtS-`YK+te1Z@by$aJ=w9B~&?L={Tu5jaTKg!$B+f#Oi~IZa(k% z?U&UL@-OPNu0geE(Pjnj<_4fm5qPJZ1U2B-yYx?<1!dN{D?Rijk19LAG})5l9lIW5 zF=+6tx>1J8UnV58WWL?5RhD@Dxm;Y+slHq!Lo^VeS)WSVjLlj!;TFRGh%vUV;kZ;5 zK$>^rim?w5dacVz!26w$P*}9DL!0!NYe?4{kn}N%k300_r_(IfO|mvd`DMZAt|C}y)Kg(a*wBLzPQ2*f zL;;iddDI>EMBE6?KXs(GKKIJj!>Q@vv#w5JKCGmDOlg_OUSwr|OWalrLiBcGa zvKd6ao|bg1e%#5#xK3)2n-X3f_PExbGu)m+F3eD0Y-_2hsTogZW4V5?6Uf*;V5@Hn z?KB|l5gOqL{oatVEegHiFD5J8+s(+?2`R8*P{zXU%RC9k$>-wX#cdJT$`Y1p3Eu(I zr$`q)Ui2f{H8KQ0%nXI9Nt8Ycwe3`ie?qBNgRO}3hW@EDsH9dh&w^@_LlXgh15g8BX*B6a-ZZ@PBX0^> z&v?Amv7X#%P_i7R1j`Aa*iRB4Z#Jw#_l6Xi5TekX4d7>Mdc9kjNTux1_>nic*elFZ zLZh|FxoN0GN`ozuN?O;u4PnL37-0+r_7zB_JOfm+sE^g^GpgToL6AZvy6A^+MzV(0 z%&mo#Tc;ha(W$iEAX}lA#%VOe7!I8%*6Nc+d`7T9_y2r4Vltq#dK8hf$r6-5^S=~L%9B|bFaM=zT4h+=q(*GVKjrejNh&CoJa0o@ z6O$;P5sG3So#=f2kD@7J6ZIpGU_6gHu`fn8wT%w8YvlYfP698TWQ8hHGgGb!qUpd8 zUzmy;bbYj6M6&a+c(11Wkole>(9<+?HzhSsO|zF@qVG;-lB(drd^IEDkd* zK7ct46W3G3NpsuQ`=Q2?mMKRqpgQqPtp(()2e4om6re;GI^N7uN|~nu_-Gt85Iu(pOiz3ZTTwqsBNPbWAElAmm2WiAwWJ$(2wTZMW}iy+$}}IQJZ9fHU{$)D zXqrT~zG=x5F^y@)@T8eGk`!l z7x$!JvZ05BHE1h84A|^f?1^kAnyVLwhPYghfsg{pa0Ro+B$TCQCTD^guI0_rYxuHq z&;#t_54u*E_YB%ha@(?vkjsH{q7MVciSEQv<}{O+rD$7iUG;gxgzLM${dEsv_4|KT z*sk~=FGiw0&~m-?aCX#0{IIMvUJdtwuJuK?^*QZOdPgMq=WH;Ye z_sbo;7u{~J7RQHMTT@qCaGcY*1F5`joRxgNu2bLBoz;`n(3D^>=G*@*EaFR!{NKlj z=s>+~xIl^{l#+l~bawH+{xPiUnqAz!BbIwmFkgy>`=Wk!Xt5L==$D7|CKr6wZwvuE ze9XT@%On~)A`#Bsf)@w;UjX*5v4y<&B}@UXW3SYn>OQz>|C;r_=*ivuCrL!Dmc*vU zEAyur{9?%I{ov*1WOH>E6*?`$3mdjK24#0VZ#bZW_rIh?avKFr$XX->8f^42&n)?p zX?j~j|D7fRTo*#ym*P)B$C*&~@sD6|j}BzKeyQ61Jlwf>sRE_*;pX`%=ihI8KJN>K z1HYb%jh*V8huhjc?O+`_9x1)vsmbjOboG7y^7y!dDO2&Il$yMUsVOV|55w9_ZISd( zS_Bv!>h$m*X%XhNs+)U2CxxEihLE{LJicBNKoY+bk}(&{;6HvH9>azG3e2 zJ;(U7^{2|1m*Md|l{Wh$HrM&{ntjEWR@L9{I_n!R=%eQH+tX8p=vx%9grVZ{JM_6q z;;ZBJpH}+ox~uB)TbZlrQ+NGavf;a-1A*lj^%F3sB@x3XYd7C0t2fu}DDcF}JydV0 zL3XdR^KjPR{dcUixqHFkn#NGa$`e+!f!G;KQ**P3J_0V-G~T{!R?z%&t8ZOmg-D_O z&a96}S)>`?#jpqBPl-X7O=`iM^33KRwmzhE5OU05=TPv1Ku!)S(T@nr$A`5KcgM%J z19RUOd!NV@*Eb_#IcHX?**k>>&WnJ!w?v<4p8gl{*cvAh{Td7*4FP42 z{ei7u#`{~?9GO7D+_@6;WTV{MVdQp1RcGTEqV#eQx|2lGfT7qUBIF-daVJLf`&@8i zo8aF}W?7zk8EAmA<3;ZXXVPMOu47`*-uZ`};N03vCt$1I;QUJCQUfWpc|y=f4g)$1L~!WWWLgBQP2p-koc`#4 z*WN;~<`(vgl%wELP7xZSyE2=W^PKh#O2!FVi~XYeNO86U$)@^3v}i#{0=wZO#cV`rM(Hgk&wmD4Uanm=pCsIk%6K499wh@2+1jw9B^OvCV;1~GEr?$X=lke9 zS&a^DVv+<7{9rgU`DV-6^Zjny@tyGTHR7BLdSO54WJYxDw1b2wUphZ`)U~^WDBkkP zqdcS+++HxNT219cJ7!=*qk^_1`xDu-9Fq627?Ss~7_yI#FhrQEDvym2JU=~)Q?PsL zXC5^m0M<^V8u}xcO_dTcgmO!jStp<5*QF->J{U^UO@+9pu^`tVPj9Mhn<6%gejt&& z`u6es&hxE4`AXaKppg5`(|Wu$?d$65s?)Q=xbLg8eB4v%c6Pu0_Tg%N+|z{~^%vJO zGPgD7UsBK)>9L;qOF1h-){l0)jlO&RZVTuPqRDpT0C47;1~xi!-e4d9HR}(qLVo~i zTB|t^nA-0wbB_DAdh{xXUHD6?%c=Y||JG$1jY^2Wb!~6brtsQHKzdb)tRcD_L#oBp zL(*e&sW0BgNxCV^_%Z&1LqdAdb!;+pdHz~I;xepPcahYA=dKeA^vK6l08~|e(34E5 zz&!3`z&AG-H9l@h@KDAWxqfzVFk*ICuwydQ(B(cmbl8}aepeJfdV!63q`%-@I$U6u z-Fr#Pbot=w5FQF}DHVaVIp6-9$V*7hPFr(5wks&Ns3b5iox{O*{&r`xSx|5w?y z*#9iM-c>HaoiLxk+#_g&pX5MNGwutMgusv2FE|!1B0@-z85Pni4h-N@%$1P4DTzSa z)#{wTqgpPI=3~hJ?dKDM=b-oGLiNpu%(>2p^w|g^C9q0BHOboxC(LR8r=YXn=0cAm zg_O{eh*!O@X64-gTyZU&_-hVA!pDSvvKef5*{+vc6Z-EE8)n=)uJ>w`Qcr&_2)~i3 zK5?eU--?23OqTifO9BXIu?f-7Ll?^KhNDGrZC*oUjeR{0dDIq}$=iYny{NL!@^gl$t z1@UD4O5%-@$uC3Dp&2{UaBNH`~L`q;e6)b0tve}qJ zWEG3{G()M;wDYJrfIBNTwka+$6@V;8=wvP$Xp#)W9Gy_+N9zRvYM${^`mLduKgmv7 zT&ob61c2R3336m)gYKj=p{GW19tj;VM8Rkt(wQeERvaOx4Fc?w(b3Ti@gnJxC(F%( zJ1F&6g6I$BMa0{YcGh|YWf6y_o{;c(Xp!!9^noS|iP$d(YC%%_;{GE)M{mD<|KxgTJ<~7EBmd*Zkc@}cL?U#NZ`+l{+d?2lV-}d~< z{ps_hW!u~3{0jG;w3~ET>a_(u`-b9Ne^I2zqsX6x!QC+fexRuClyG$i#@33=@ROcw zw{>?|{ssS#%0g7zMrJ&C^u8u4%g6aFo_d{Keb3BMA?`*ON_CDY=+o4LZA;b^dd;3XbXz%h$_N?7uPur-knT4al{%>V zdb-`DM`tt@&1NmNh5IR;*pkzX%&m*(p(S+}Z?z0atst;4!6Bh06b`8my_|oVzheQ8 zQ@oizO4a-*8Z{VO8W!|Rvl(@Y_<_@F-JwXBrn^X1cObpxmx>r3L3M93sKzlVpbUr* zQz*)Wbmht35V!2j92~K~yIteJj}Mp!#m3R?tpgv7;~{C5fFRHjO#l>V@~JgxGxM?% zWzrB4zwW2&H4Ce;F1imCZZ;)jzbTB+GEYlGK+>6v*7r~#6&1-+&BNijYodPLD*6O; zD{u_vNS?|;|Buq{DY){kT^oJSv2ApmbZo0*+qP}nwr$(CZD+>m*y(8JdET}5T3^*y zwGZ~mIGE?NYW%Np-`8*260py!SuXDvv#(ZzX+}EfTXZ`YH&Zp5p;9?_UYyS#cBF=U zt0C$?2?>-<>?Hhg9MOSVV$u9jRiayhDTWGgu{UkJDb*M%kevo$;-aT$J)LV=Qjp*s z7olW=(mUt~56zA=^Ao3ZOd@h+X{Kw}qX$Jc(p>MvMF4lz{NjNJuTqEu|DkE{Bsp1z z^S%uFWYY1Gx$^WJ66QGPV`k~wI#gntdr#5V6=}>g`h^-V)V>Qw18Tf+jf5d(wZ3eES*Z%Vp1g-Ytjw#k=NW6IrHskR{R zPP>ZC6r^gDw+=vXcwCwOki~61>B!bZlNn2JePR5%A7sK8eUid=GvzDIM0{FZrn7D$ z>sUj_d8KXaj!ja_Vr_ZOb?RjHGtJuH{h*=wsJ5@+PIfrrj&9?9*L+1jdmu@YLWF1a z{OEol_`sLiej40fmQ2HVe#o}5I^T?Eo5&{8(G4vN@Lni zDzqmHsO1pvH?hnA_1oDKY|y6^;;;F4JGFQ$j?TGyuTzLVIPeYb=tZ;=u3cHnI?j0T zef~`dK^GsbR=N{dhNWU89 zfHENxog#m+zx*=`%klk@U4PYVas4i9uH2zxZ?R^3OGr8%Rop-@U;KUXU(v%7dx5L8 zK(`yJ{6RJnm%SPGMbbR;^UtFEijex!y2|h0p%?o9YY;Y|-`Xyf^{xi?fl3tq|1t;* zv_*-ofTdIkl<2B|w&P-RhfZws*R2s6_ECp^=>0V{@AA2uun@Dw$=6d;C{KvEm%wLx zq%HmuqqCDv;)7hnD_&mbcOkIwnAL@6=mB%2E%$sDK^IO5<+FfWshg27#;KBlVE$rr zeWnr%{@`C)LB=4Ol3FbiW5BwJeK1+C)YBOg0@Rz6ed_+U;NO$`li9a|tq5(U4%5nS z$BdH(932R2t+L+or%(@zi&^fBW@wj_(7CpudUU?U-xJ?3HP(OBKNL2C%+B0gceGN2 zf!qYoH=OhO&NVAN_}+%kNH>q%$p~PtwI=XMLtooT38qYLCRj03AZ4jOg$L zNCXMmKwyy)DnzuVnQ8KOS>c8Nw7`C&w=$BJmIPBuHyClBvFnRVG1 zL>a7q!aJcxRT=(%9J3-XUc(v05nYfF?IFFSBN?Qc+5_lD^jDSWGjPSOzNBU7?{+ zK&TBNMJfqr$j5>;(HA5)q#%1vnj%Dyib0gui@=~*$bg`4j5`mzP#`meU1}_|z$P1h zK9;A&j1ZBrxFXQAA)wp?Wjep%iovc_PiZ9jlX45fy8$vbHaCGH18!`Egu6y}TRruj zaUWU!`C<1%_ou?5nh}A)3l^BTU7*aw5}VxzugoH3D>S;eG$yrHfPpDUc|TjJxI)N) z9h_jAOod*zT6$LnHkm_VvL;cx+c-wIbtKVUbe@Pd;rYV@oi$1eWzB?B;3PN_tSE7> z_F&g?naeS#$x?!V;x$|07X2Q$tgaa|n;zje}X74PM_iky6N5DSmE0)@@p7S0lb8&Yg^PJ;Ubx~Uvg~~D zG+Ep+J!Gi#B^tpztA&kKp3+Xb(VRExi|-&5jFG-nNK6kb`X7-@*L42ALHjj2N3G%x zcD;P?kg61XN)<=l&UPAz@B}CR`@VAmPKZA+h^C~xnXzHkW(s~(*}JmDd=p7ol*7T? zF(y#pZ5d?U-be-3LW_|hifw(6v0w`iN*Zy5 z=*7~&8kQD2*+P#GNuoXCa76!Is%95gFsGxRVFwFMlVWAw3(V{+cnU zW&W~wJ$}R=&&{r9{`b`seFLwUa{`l=!TL0a4IqS-o2)v$9ps1o)UDE_jh==xvXL4) ziPl@&Mkv)#b|qMbTVczFBMH2LE|K0WT+e1=apd2we0x^PgEke;)Jnx*f~?0QTvHHr zh~4Qa%X7%H2s9hpK+pQG>rvrk+AhNfdj6+TlNbn3oAY}Y|;)QzCl zTJkf0fVe?^SyvN8f5HH8ImsSZBshW#j$W8t3K8wK zPdm`ywR&k#aaX2N$B{9dvrfHl@8t6E0`^R{fRj!Rh5VuBfSI{=G{5!?d>VEN%Gz1y zINt~xM+!xqOl<&g+aj8kj!KoIO$1w8DU#(Jc|(dXBiaBP7ytHs#UUGbI3%P%zbTUt zSSan>#?9ZZq49*cItgY}&g!Y7Zx8ECjAZ|Hg$2W832)QPCAD+uw+mQGflyK_Ngs{4 zb5G8m8xOMdLxxA#|N3Tv3V#dtBoaX;x4TS(&En-rKjm|eIS}*ZpP-^>QF7SJ5=%bKbuP%ogGA$?>4o3U>RnR;O zS55Dp9}9?qswFHJ|Be$PB~Oa$I;}AbY*-O)|EJ_b`!VOuR-s94KCqp=YMM=N0{ zAfFh8P_$QIMGJoL=cW>OJp78- zGIe!9FpLT`H>sT^cTBL&KDDoA^i}Dw(9Xb{bEenID)ciFL z(korBBP?75AQ!4Qprj@@G#nz%R@l0Jx^G^H>8xT`H*Q5EE7@F>-?G!3S<;}7THxM6 zQddeAP%F&Gu(N0lKrbQf8~zR;eQ7byZRX925T$G(=9$z;&Xc)T;~E%3yU%eykk6H9 z)$)sKx4td(=pbNzAURTizvMAdmMZvys+NJc8jdt7$vrLk3)Q+=fP(uc^`>SpfSPRH zFtB$A(TReg0$ThYN#^ce0}##-8s;M=u$&+!5}BmnMQSPZ%(r6AuP` zc^kJ}DnXnU??SC`*ghGZ*Fv3CJijijY-}xMcK)4-R4?`cF9Li4cw>=2m>QWH4jD_k z4%%$Tg$^Rj;-HRHm4Mes)(nhB_N;sy56r`gOK@ryPT!Cy^zuZ{^5J8u$7DV8hSXty z8J?~%C}+lUtE}W2MnoGtj9lZSOgEfHT|3k?wWf=!fT2q7nCE@`VV{10leAoD^3ojE zwHcaFzkry`pv-?el0LK^{l0xj+Y!}L5XFJY#u68$%_ZW9njXNianC;Ir zB95-3AqYz8789)27Jo>$ixb}hppIo3J3`er9A^U|2H`8cexlLEL# zMB48s75o({s!h1*b*Q&w14V!uW?_2sTRfUac4br)jRdh@KhuwUV!>1gs$pI(CqH}G zIs(OEmF4fFj;Lir=gm+}D6j?OL#x$q$2_|%Fr5PLm}U<7o1H zI@BKYe6p&3Y1O=WMDHkTK}t1msjh!G{~*5lH{ zY?PXmG@{fe2T@i~4Nx9zB8~$$-2;+Sc6@-JaKb*DkYfP#%Ls>{b*pf=q-6pU&ZWZ$ z$M#k_CdwRMnp*YBJ-^wxt2L^XXNi!@ITOcrjJRg0hKf4G+BR>-cnhPu3ABQK&G}6) zN|pQ8j+rE#h>F`#kIIXD79I4k1R{HF(^Cd2U(HDVK2hiE)MjOp7vC_$j6}hT(R6BX zypNozOeRn`8XE#co#22XuuK0g#HY2H4%y7^F)7wyed=b@hmPQOd>Bb3vI|&>T0XyguYQvK+4n3EVn+E$*9lT?VO*(NYg=8i3-M zor`%=Kt#YMSQ;qB*@t}x`uEX+ZkbaU8tx5A4Eq5&VJ|^Wo}LRj&3PE&FDv%IdA^1d zv7i^d#jz#sBe17#8xBh3^R1MOo1mzB0%?K!NLWXKJaHmOohWh*u}C+GMDL!Fcxg9E zgaI>dbojFEpmWhCa1P^^z7Xp0r&!(%r^49vgZpa$y^+|J!WCaUZjpQTVZ_1ewfd~C zRi?C`JqVad+M$+}a!`8OY^1Fyc9E9|rlznzars%;5m(ziSqL**Ztv!Cv=PW(76JUg z6C^+cgk75EWmEYg7(4JH{Iy8ZM1U$LG+ZBWXP@z^_(zuqC%2;udZ ztxBXkgVS~Ct9wtM(~6JBTYfSIR4U8*|1NCY$rKnbDz#?9wQxtLwAgk0r1_|Z1V!q% z=K8&W5R>J?f&Kr;-WtRX8uJ^D`h8YKZjc*XtHrNh{SMxyAYQugjaVdJQn(x^g#4rTvEXlMsBsKN_ueCnb@oNfc@9b&b{#l z=N$XD7G=FG)u_?6%&b5e5M9LvR(aC}J`I!OqVH`?k8pcxkPo>o>f$xLtjuhT(kV1| zQvPZ385lcfPCPt?%H=@Cr1|p?enpwVlB+A~3KG`j5E}DtC*M*H_4u(j=C6qBu#!v% zMR1PHRtFo|BPSh+f@7#e<99s|O2zVgIj!N#LhdOnOHLy(-QUW2D)zh=i}RyC&$&Ly zN2e+eWH+n8^5zlx=cyY4xV+lUp*25&?@4n8rSO}Jn0rvf zE6BYw7LxgbSzQ~R?fI-;qFexo`(swtCJRX8xHCN~dx3+CG=>m-_|?)b|i zK431}D!$pU)&XLQycB_RRto1^(BL-bDrleq0}q1SC9~!>Cd+`6y1g;-8nwfFC1@gIr&)5R5JeMn2}gUanp)-x3R32@PX*oKBYPFMc%1v55XDSaC|J zI-{U8?NyW>mRXVISD$x{(a?1#`U_1#d4Ed!UQb;vW&PwiCH=|8RcsL(u!C_%y?z}g zn+@->boL`qpfpgEC3?qWXjx-Z?JfV|w)NwZFW0Y(D?CJZLO1(${r{M$c)I(qg79vF zu0+ykQFne?@bHt5xFLI$r=6l*g0n%;#TGZh4Ri#lP3-Mk%oA&9(@m9u^%nO^Ynm+S z_iUR=eZ6ULlB_~{g&|%&Oea+ps&~KmK@oK~Am|tY0qX~dPO!x=r z8Fg@i)&C}i`WKTGR4v|4n<2`BL~fz{&*+5-1H#Xf_T!iTbhz|$d4H>Bt*xy-{DF@L zhZdfFI#R8&F$mwC)p*wZe&yq%`-D=8_HS_w2e-@#YFS2zTM8p#l|iO<0Z3b9s4A;> z3oneFa0!Tc55!Xp&I~iCM&a}Nm&#{g6~qVszZzWR-+sM^jL%Yh2?v=8`QmK!d{11& zE5wWXJ^nj!;ek|p^B1DsSu~A+-WWsjhIX9E7I9k$3xSl03~amV7AL9z{Stf9(>-*& zYUol#KDt%7cu%waS64DuiF^DG`n_{)_4q1zur1@PfS*q2_imM;^rY^g%1cIi7r(3W zVQk6-KXB|NI|V6=RK?LuE~GGY)X+F&p6S_M-H(Y3X5ahK2n?CaRp4RBrD-kya2bXD z_Y>PnTK+#pACcc(P=m>ULBMZyO-*8mj*Vl}H1~MU{&?>Y4r-j}5i}1B2B%ane)kvZ z2LFX5t_Qv#f!w<$d)S|ap!Nmicb14q9~ztWnZC?xK5kfW?j_sIZAkm;LPRgy6u>_~ z`H#^A*W-0t@0O>+{!EThSDP-B zC1ClNo>J~iAZzg+2vi;*S4FSitBqt!DHwndr{IE zM0p2m_Bxai!M>YEY0$@Xm2{!Kd%A?VyyRw5JH}0Tjldjc^IQi+f(&Z1D$d=*xVX~* zM<8|%&Sahkl8+|N=z`&Bz8jRrgL%JLw>7H3sXjmE@bRu7VTy;p*RfxJ}qSKYOq?~NEk2Rw>%nI)`D<9&DDAtHeTBfd$3j3 zYGn=a1r2>l-=pNg`M7)f1Xz&=g5I2aJM>K#*_W;&?wTn`h_zd{wDP-V$WcaxTsq=g z_vNOOoU5<|(HoN~)|k3D^CHy)%rIB~P9yY%kv`F_1qAa0$d30v?O^J`fv-4`p^}8xS>(h zsYNu2pzmizrv^XX{q39ZKj*Gd^} zoh-s^PD5H|qEi1dot(6#Md6imgw}*=F0liACkduYbCh>Tdb}Px*`RVzZ)CD+#IK5m zT{r4ro4zu}WaxGHJt|aqKS1aoELG%Z-Z@}3mvu%*>NHMStIbiva=T2M`~xjPQ+CF1 zx^bq3PyMxLolxBo#p_R=`og}eFlV5hTe5cGQ$us7{=kxk0ZrMdrCR;1silUcms=el z1o68*AgxSR{F=6rzFywt1R(d_&rT!~#!`AD%e0#~j^+ z5_jrY?9YgT1YAP8boKqT{oH5YJU<(wlkkATp&k0HBcXnvqRFjsa_HC_`o5|wL)e;k zX8r@p48yB&g;=mLjzJ!%C+;2t^>86Gr1A3KpGfhaT9h(E8^3cl$Bz$bxWU>s(BJLf zN{-Pp*RhlIWlFF1p96?Te?FlNw z=Ta?Ws20wA3*uogu3Aiicw2n`EkAtBs~bxS`2Fkz^AAh>t1C0x1VA>pUubq|%<8P_ zLdAm0e#=%`(w<55kJ|DWZ$oJ(EBkm(kt-FPCbr468n$4G z5l#0aa+;*}P5RoTga(WuJ(uvzm^HYd_WKhl_7hAax{^&HGElY~Gqt+P$~If<3OTu^ zyPvH0*Vo&33;W&M7Zh4l`SllH+&>NNy<48$ot8UayWhXm0=|#c=dV=zuigunPWE$j zwmyUxDEBo!m~xB*d@kQxg7P=EKOfJ-TJ^dE&b~C{0``buemAKyx60;{IcQ8rl*;7Y zu-FdCxKIy7a>kfjdsx=%m4$?zS78o-Wn?-E+oN#VVwS7AN~#NguBFsq#l)7$Di zh^aBLeqO&sFO?Q%REV?;m04l`5b@wBRF9NMmZ>wTkbs=kbYsio$RWnFmZ*oq?AC{C z92eN}?O{tTTzn%fi5pF5e%(TnwhpMLZr4&mm`|67e2>|JC(1{?l4v&|cjAk3YLjVP z|0Ixwhcd%iDhACS8Nt?!rp4vZ+OCl*jfQ*S!2wapF7lq0avW_H&t>4)X=vh&TR3_gVIkswxqM5egclP9aMwu-h#;(y;ijHQ`httOahI zDE7`?^P|qh&pZ@;p(%Wy-}3|`2TC$H7xqxZBQn!!cG3(Y6|SOe%zEFz<_%dAY7xB9 zZzJN4d6q+zlU0jy+z8C&mw;+at_C!$G~o{(L%iAM&8MDNXpJ^umcLKW-Sc>2;Y6qr z{XU+qV%?N;MakAF@sTd2aM>hzTuxg1KpaS@>UK1(0B|b?|JB-z)Mx~1rzTyJ#jj}J zzuo#HGbfa9%{D7j_9OHo4gL+y*(P3HZdmYf-qd*cT1r5Dfs_KmgF?{ z#;H2BVnv_ItYnR84ka`X2Y@S38cIHp1CmaGmfz}?nhhl9i(iGL1T>n^1ikti04+hunpK$k1x>&2nY6I--Ffqw_$-DcJ8g zd$J%1)Cv7R8jtm)QGr~Ljv!D*mQR?x(vPicjPJ_rkKP}jDYG;v3JJH)a++2 zs9guaPRNSZfb7J>F5*|3dU4F&QqZUd7%_l7`J?K2FfNvyzR=$C$;;x`QA90Yo8KLhdIJY=?HtB z*<$ zGiX%G;SRv5k7eR9Q3v#dzy8&Wl1fXTq#-?4OgIyV8nR1uB*AAsQMTuG9_V^+&kb@X zp~v?e;ck!b3TMPiu(Z0E8{iguIX(slLWhIDJq0%1 zIqB!DZj&h8=g}pe2+iaJrwBq5>FUCt`{jnRr5%K)RhUT_cv%mZcynghc>9&%>+yAM zmHZi&X8CE(xBasCy=yR%dxL?yL+~*j?Hk^0e&2v&M@?g}Z(gWd;JKqYs?=a~%&n!-{AJOg z>yS#^X5f4;Q6sD0i%9(YA(TVmXMeWJ8aO0x8c#o-{fq`RPm;hX> zsZdcTCrB+!x0F;{R`1g1g!xT458H}~fgVAJA3&qWI7Qg8_lR$vjH^8Z%-2#v@5^s% z`w0tivf#3gVj+!Sh7hzX%|PEnVkEnNbWcR+&xw+|ZxU~>%EZ1G%l-*vi1JOd&fbj{ zocP^9%hC4_#f+Uw4;6@11H>_zP*M=o%qJAS1LKgYv%F($c?^hNjzmR4lkY!3VP92bG|3B{Fd zV@+cV9I!J?f=_zbwoLTs?II2?Wu!zjra~q7)=WEemfaEF|3sNGDywfjk_QTk%CsNdW$OFJ=L$H_Z*NkXw;tJHgIUgugc_0TSzKgp{EOtVhIzXAYViJo-i$ zZxY1%TVzzLs}cRV#(89rZt%s0f&_@B$J!=^W&q7@RHS5J41t5dSf$!jtI|jbh-j$L zQY|ko@#Of}#tC8k0L;Xt8{IV9&P3igFr_h|E*d-;X%89)Yt0Y@CagDdrkw z?WpN!P1dcwc`q>=|9Jb6KAP5;%+X8g+w!!(j2t=P<&XC zX7v>ai|~&o3K?RD*jDTG(PW&7dn5eXdtcw(S6|hfFC5#mrPp49DaWtZURT|oEpOxF zubs+!-|u_sz3=L4Z)*HkX6Y#$t;b5%WGgUpsn?{(v9aciaf+4uO3{$Ur@2hB0Ca@U zbtFm2%AFEGp~6&5}$h zVjunab%kI)WB0GS#&(<*w{IXL=>4UN*P$}{l*y1-q5pH=-q(V4#o6r7Qt105=ky3F zo`VUvbD9(`2wcIuC7FhNg0e+dQcYtw+z* zc7>HXNUiqP79y~zCu#M;!Z6_1Ywow{kdgAgMQT(!r7!zilSX-=tQ5Q1%#@{dRoVtb zhQj4#*#!X6Mpk2Kt3Yh%s+2B@I;%_V(Wf6$n)=M^+X|UeP0&`vtuY&kXmN91-m$Bp z1rEbzoIP&0Tb2fhQ|lpfKPZ8d)7fEsw0CteoFm3rnb2;1K~d}o^lB^zkK9uuhQyD< zF+WwX! z*fACNI{MNa6s@`eSsOWTB?>DPuT!tjP@z$nlEJ&BNguFG6!|C=(Vj@#$J5=F=z-JE z!v2lk$r>{9-RJd?)f5Qh0D$}iAuPx{YH~LJteaT(9kmtn_|hieyQn*AAqb53XFJt5 zZC3Dp*d*fl-pS5|t{yqaE2)0m72nV?xn6~sS-+%wZIvmM;3@wLHf;Az#W3J-;hM?7 zCZpl;6$b6k>d7_Jlrl7>nYdc{(jL>bDX&)2vSu1MN=hYd;!RwyF5}~S_VAR8AWO12 znN=?@&2)QQ?0s}QwOS$UMiBB%Y}fl+VA$8%CIf&^r^iQr)VB(t?*0y;+zq?XsZSU2 zhds{I_locH;B_*)`$Xh@^gh-3eUvJP^RqDKOU>Y2R0qrRlMu1^=ILD@r3vBo#-@c} z8k@a7tKi;3+w<*T0E~gd6#s(?+4+zgX(h$xhmwOZUBn=1rZfPOdpiJw2Lh4u@gfKcp647q46!GFvoJ( z#^y_WhD&E#i~QDQ#2!tG+82>gaw`Pr{^eBc5a-Y-cl-;lgTL?CrygJFKOy*Y#H6Mm zx<37o?N;@Z=>Y4X^}ea(08rH)k!br{l2M3<@hq5ktHC(Nf?B_|JVp~#ehFBqwwVechWWseW2qD*xa%9W9*|%7#ehNraHK?3n z9KTaL{g66j&^Y^`C)7cSbUX%ZzHrwz2SvHH>KlO6l;v>s z-v#Wwi?oR2?GM$diN*q8k!s@Tl=^tz*p@}*zt~nrv03s(PuorDRo!{QH(0WD$L2w#=J1)2X0fBk*)QjnHCq}Yf3{#*8;j!Rb!<9U>1&6!_KegoS>gtt0D;CcAF1x} z7kk3kh683HC^2YIYnx)tQr&*4);8Be%LzgA49cH31g9CK- z=+eWR7zq7;+0ye={3=I!3h1S-QGGgh1QqfeB#qysRj+QXb)fe{K&VrtF)(fcpf3Fz zoBQoi+V#M(YP{w^hJ7YCXUl0dH}Os8Xczx37Tq3=nPs|8D=N20(gJXF%_*Ixcw5l7 zciq$1}(i`4fP)p3!mAxtKFpQb?P7#y+eY$ z+;alE;{2cRJXnVM=10PWD(z6C>Q>uk3af@-ZABUx-uP|fn?querrx00nn~cnhA;&9 z`u~c~mjmCA!85}zSwlN>?;^%YsKO$ySl)qMjSipno*JI61FuUEy(%d{g!t~03OJHH^Z-w6=1>~riBEr`; zSjy?NxX`%sH>c!n2hFe685mw3#}K*uNC(7|Usb$LO_K-6{dMB>Nw+5!D7?7Q{LvC$ zVxm&bXxr{c)K6=}DiszM_Z#i+Pc{Q3Qx0|20RgqCEHWx^U{=16aQ!YKK~$M`g8m@P zV5h<;T-*00#?bgsN~mAk75l%0#fSCAYo)r;qmwFw89A@M8dhOl8xP-T{9+J@Y>G!m zlevP(&`L%Jjm`I|(EvyZa|PC51J$By!LFyd%Jq5%gBwdi{5x~M*%-N&fcn<}J?794 z77TQPvPEI30V_bjC2?5Cp+tAvR>?PMC&0v^UEtV$?$2;$ysI#-6JtKllF=5yN&e-v4(*d>r#nM7*_xv0nn+ZH0qs1eJ}F-V63m zNZf4V`A@q3s9&B(S5)khJ6^~Gf4tnYBx z@1JlO-sazMxaT_@c5AJ-4sphCm0bKc9A0bq?{IiRQps3G(o7JmQT?VVkE=Ji<}at^ zqml`(u@cKF#c5iC@luQA9!B~P69aS@xak>6+J$>xkmXJAimZ6%3mWQ3{^3L5Whz9e zVn@lrDlEz0V@XxTtvVo%x++Tt0w&jj|++io5_k0%@`VFZapQ9h#&Yz*2UxSQye02vIZuF4t zX#Lj*|8Y;ss5E6DQ$B(Jz}6_sfYEPPe*ui+gU8mzR%6^XtIkZU3sH?L@9ym7Q{b1J zjoLGj82N#iU4xbS!#H-iKbmDeMag}OX^5NKu zoLEuInnCGrEP?~mm^LffbBH)Hw}CR=LxzPIb(bb@*LUMm-uf{$5Cp$`A1hY=8L)`{ zlm+As24GtZfBocnuKnuu>Ur~Oo%wQ+m975z=1siMzTSUvntw0QQ1u|1_gR(nYpMYc z+-x#{p`Q6-yaFT~#_~D4Iw}HMsGR^2=&@d?eQU`. """ @@ -395,16 +395,16 @@ def prerelease_deps(session, protobuf_implementation): # Install all dependencies session.install("-e", ".") - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES session.install(*unit_deps_all) + # Install dependencies for the system test environment system_deps_all = ( SYSTEM_TEST_STANDARD_DEPENDENCIES + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + SYSTEM_TEST_EXTRAS ) - # Install dependencies for the system test environment session.install(*system_deps_all) # Because we test minimum dependency versions on the minimum Python @@ -429,37 +429,44 @@ def prerelease_deps(session, protobuf_implementation): # Install dependencies specified in `testing/constraints-X.txt`. session.install(*constraints_deps) + # Note: If a dependency is added to the `prerel_deps` list, + # the `core_dependencies_from_source` list in the `core_deps_from_source` + # nox session should also be updated. prerel_deps = [ - "protobuf", - # dependency of grpc - "six", - "grpc-google-iam-v1", "googleapis-common-protos", - "grpcio", - "grpcio-status", "google-api-core", "google-auth", + "grpc-google-iam-v1", + "grpcio", + "grpcio-status", + "protobuf", "proto-plus", - "google-cloud-testutils", - # dependencies of google-cloud-testutils" - "click", ] 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.protobuf; print(google.protobuf.__version__)" - ) - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.install("--pre", "--no-deps", "--ignore-installed", dep) + # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` + # to the dictionary below once this bug is fixed. + # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add + # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below + # once this bug is fixed. + package_namespaces = { + "google-api-core": "google.api_core", + "google-auth": "google.auth", + "grpcio": "grpc", + "protobuf": "google.protobuf", + "proto-plus": "proto", + } + + version_namespace = package_namespaces.get(dep) + + print(f"Installed {dep}") + if version_namespace: + session.run( + "python", + "-c", + f"import {version_namespace}; print({version_namespace}.__version__)", + ) session.run( "py.test", @@ -476,12 +483,12 @@ def prerelease_deps(session, protobuf_implementation): ["python", "upb"], ) def core_deps_from_source(session, protobuf_implementation): - """Run all tests with local versions of core dependencies installed, - rather than pulling core dependencies from PyPI. + """Run all tests with core dependencies installed from source + rather than pulling the dependencies from PyPI. """ # Install all dependencies - session.install(".") + session.install("-e", ".") # Install dependencies for the unit test environment unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES @@ -497,7 +504,7 @@ def core_deps_from_source(session, protobuf_implementation): # Because we test minimum dependency versions on the minimum Python # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras that should be installed. + # constraints file containing all dependencies and extras. with open( CURRENT_DIRECTORY / "testing" @@ -517,16 +524,24 @@ def core_deps_from_source(session, protobuf_implementation): # Install dependencies specified in `testing/constraints-X.txt`. session.install(*constraints_deps) + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and + # `grpcio-status` should be added to the list below so that they are installed from source, + # rather than PyPI. + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be + # added to the list below so that it is installed from source, rather than PyPI + # Note: If a dependency is added to the `core_dependencies_from_source` list, + # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. core_dependencies_from_source = [ + f"{CURRENT_DIRECTORY}/../googleapis-common-protos", "google-api-core @ git+https://github.com/googleapis/python-api-core.git", "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", - f"{CURRENT_DIRECTORY}/../googleapis-common-protos", f"{CURRENT_DIRECTORY}/../grpc-google-iam-v1", "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", ] for dep in core_dependencies_from_source: - session.install(dep, "--ignore-installed", "--no-deps") + session.install(dep, "--no-deps", "--ignore-installed") + print(f"Installed {dep}") session.run( "py.test",