From 59aa234306f31c37cbdba7c10cf46835bcd756b0 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 10 Jul 2024 03:53:05 +0000 Subject: [PATCH 1/2] feat: add `airflow_database_retention_days` and `airflow_metadata_retention_config` to message `DataRetentionConfig` feat: add `AirflowMetadataRetentionPolicyConfig` message docs: various documentation clarifications PiperOrigin-RevId: 650807119 Source-Link: https://github.com/googleapis/googleapis/commit/ab6ca6a75fa8e7872f76f35021cc669e9f36c60f Source-Link: https://github.com/googleapis/googleapis-gen/commit/63906a19d3c5ca318f0fb85d9cc3188e0cbc5bd8 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLW9yY2hlc3RyYXRpb24tYWlyZmxvdy8uT3dsQm90LnlhbWwiLCJoIjoiNjM5MDZhMTlkM2M1Y2EzMThmMGZiODVkOWNjMzE4OGUwY2JjNWJkOCJ9 --- .../v1/.coveragerc | 13 + .../v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../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 | 155 + .../airflow/service/gapic_version.py | 16 + .../orchestration/airflow/service/py.typed | 2 + .../airflow/service_v1/__init__.py | 156 + .../airflow/service_v1/gapic_metadata.json | 407 + .../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 | 3029 +++ .../services/environments/client.py | 3388 ++++ .../services/environments/pagers.py | 502 + .../environments/transports/__init__.py | 38 + .../services/environments/transports/base.py | 497 + .../services/environments/transports/grpc.py | 964 + .../environments/transports/grpc_asyncio.py | 1084 + .../services/environments/transports/rest.py | 2986 +++ .../services/image_versions/__init__.py | 22 + .../services/image_versions/async_client.py | 516 + .../services/image_versions/client.py | 863 + .../services/image_versions/pagers.py | 139 + .../image_versions/transports/__init__.py | 38 + .../image_versions/transports/base.py | 182 + .../image_versions/transports/grpc.py | 325 + .../image_versions/transports/grpc_asyncio.py | 335 + .../image_versions/transports/rest.py | 533 + .../airflow/service_v1/types/__init__.py | 148 + .../airflow/service_v1/types/environments.py | 2969 +++ .../service_v1/types/image_versions.py | 148 + .../airflow/service_v1/types/operations.py | 147 + .../v1/mypy.ini | 3 + .../v1/noxfile.py | 280 + ...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 | 3851 ++++ .../v1/scripts/fixup_service_v1_keywords.py | 199 + .../v1/setup.py | 93 + .../v1/testing/constraints-3.10.txt | 6 + .../v1/testing/constraints-3.11.txt | 6 + .../v1/testing/constraints-3.12.txt | 6 + .../v1/testing/constraints-3.7.txt | 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 | 15930 +++++++++++++++ .../gapic/service_v1/test_image_versions.py | 2739 +++ .../v1beta1/.coveragerc | 13 + .../v1beta1/.flake8 | 33 + .../v1beta1/MANIFEST.in | 2 + .../v1beta1/README.rst | 49 + .../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 | 3261 +++ .../services/environments/client.py | 3620 ++++ .../services/environments/pagers.py | 502 + .../environments/transports/__init__.py | 38 + .../services/environments/transports/base.py | 525 + .../services/environments/transports/grpc.py | 1019 + .../environments/transports/grpc_asyncio.py | 1149 ++ .../services/environments/transports/rest.py | 3215 +++ .../services/image_versions/__init__.py | 22 + .../services/image_versions/async_client.py | 516 + .../services/image_versions/client.py | 863 + .../services/image_versions/pagers.py | 139 + .../image_versions/transports/__init__.py | 38 + .../image_versions/transports/base.py | 182 + .../image_versions/transports/grpc.py | 325 + .../image_versions/transports/grpc_asyncio.py | 335 + .../image_versions/transports/rest.py | 533 + .../airflow/service_v1beta1/types/__init__.py | 154 + .../service_v1beta1/types/environments.py | 3146 +++ .../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 | 93 + .../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.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 | 16831 ++++++++++++++++ .../service_v1beta1/test_image_versions.py | 2739 +++ 216 files changed, 94245 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/__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/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/__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/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_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.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/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/__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/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/__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/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.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..5a08580483e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/README.rst @@ -0,0 +1,49 @@ +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 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..135df39e1f89 --- /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..ed870605e81d --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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', + '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..9a4c18f2b473 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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', +'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..3511b1f8d28f --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json @@ -0,0 +1,407 @@ + { + "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": { + "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": { + "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": { + "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..e10a84931fc2 --- /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,3029 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 + + +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 = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) + + 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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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. + has_flattened_params = any([parent, environment]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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. + has_flattened_params = any([name, environment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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-3.\ *.*-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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, user_workloads_secret]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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, str]] = (), + ) -> 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-*.*.\* 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> pagers.ListUserWorkloadsSecretsAsyncPager: + r"""Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([user_workloads_secret]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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, str]] = (), + ) -> None: + r"""Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, user_workloads_config_map]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> pagers.ListUserWorkloadsConfigMapsAsyncPager: + r"""Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([user_workloads_config_map]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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, str]] = (), + ) -> None: + r"""Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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..a66975dbf31a --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py @@ -0,0 +1,3388 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = EnvironmentsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + EnvironmentsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 + + 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]] = ( + type(self).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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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. + has_flattened_params = any([parent, environment]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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. + has_flattened_params = any([name, environment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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-3.\ *.*-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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, user_workloads_secret]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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, str]] = (), + ) -> 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-*.*.\* 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> pagers.ListUserWorkloadsSecretsPager: + r"""Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([user_workloads_secret]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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, str]] = (), + ) -> None: + r"""Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, user_workloads_config_map]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> pagers.ListUserWorkloadsConfigMapsPager: + r"""Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([user_workloads_config_map]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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, str]] = (), + ) -> None: + r"""Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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..38e83b47dd71 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py @@ -0,0 +1,502 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListEnvironmentsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListEnvironmentsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListWorkloadsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListWorkloadsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListUserWorkloadsSecretsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListUserWorkloadsSecretsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListUserWorkloadsConfigMapsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListUserWorkloadsConfigMapsRequest(request) + self._response = response + 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, 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/__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..de3645dacc12 --- /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,497 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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, + ), + } + + 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 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..a16685f661fd --- /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,964 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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-3.\ *.*-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.grpc_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 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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def 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..7c60dac84081 --- /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,1084 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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-3.\ *.*-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.grpc_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 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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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: gapic_v1.method_async.wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: gapic_v1.method_async.wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.list_environments: gapic_v1.method_async.wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: gapic_v1.method_async.wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: gapic_v1.method_async.wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.execute_airflow_command: gapic_v1.method_async.wrap_method( + self.execute_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.stop_airflow_command: gapic_v1.method_async.wrap_method( + self.stop_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.poll_airflow_command: gapic_v1.method_async.wrap_method( + self.poll_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.list_workloads: gapic_v1.method_async.wrap_method( + self.list_workloads, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_secret: gapic_v1.method_async.wrap_method( + self.create_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_secret: gapic_v1.method_async.wrap_method( + self.get_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_secrets: gapic_v1.method_async.wrap_method( + self.list_user_workloads_secrets, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_secret: gapic_v1.method_async.wrap_method( + self.update_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_secret: gapic_v1.method_async.wrap_method( + self.delete_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_config_map: gapic_v1.method_async.wrap_method( + self.create_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_config_map: gapic_v1.method_async.wrap_method( + self.get_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_config_maps: gapic_v1.method_async.wrap_method( + self.list_user_workloads_config_maps, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_config_map: gapic_v1.method_async.wrap_method( + self.update_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_config_map: gapic_v1.method_async.wrap_method( + self.delete_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.save_snapshot: gapic_v1.method_async.wrap_method( + self.save_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.load_snapshot: gapic_v1.method_async.wrap_method( + self.load_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.database_failover: gapic_v1.method_async.wrap_method( + self.database_failover, + default_timeout=None, + client_info=client_info, + ), + self.fetch_database_properties: gapic_v1.method_async.wrap_method( + self.fetch_database_properties, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__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..03635a58f280 --- /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,2986 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +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 .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class 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_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_create_environment(self, request: environments.CreateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateEnvironmentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_create_user_workloads_config_map(self, request: environments.CreateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_create_user_workloads_secret(self, request: environments.CreateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_database_failover(self, request: environments.DatabaseFailoverRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DatabaseFailoverRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_delete_environment(self, request: environments.DeleteEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DeleteEnvironmentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_delete_user_workloads_config_map(self, request: environments.DeleteUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DeleteUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[environments.DeleteUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[environments.ExecuteAirflowCommandRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_fetch_database_properties(self, request: environments.FetchDatabasePropertiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.FetchDatabasePropertiesRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_environment(self, request: environments.GetEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetEnvironmentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_user_workloads_config_map(self, request: environments.GetUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_user_workloads_secret(self, request: environments.GetUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_environments(self, request: environments.ListEnvironmentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListEnvironmentsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_user_workloads_config_maps(self, request: environments.ListUserWorkloadsConfigMapsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListUserWorkloadsConfigMapsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_user_workloads_secrets(self, request: environments.ListUserWorkloadsSecretsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListUserWorkloadsSecretsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_workloads(self, request: environments.ListWorkloadsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListWorkloadsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_load_snapshot(self, request: environments.LoadSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.LoadSnapshotRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_poll_airflow_command(self, request: environments.PollAirflowCommandRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.PollAirflowCommandRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_save_snapshot(self, request: environments.SaveSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.SaveSnapshotRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_stop_airflow_command(self, request: environments.StopAirflowCommandRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.StopAirflowCommandRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_update_environment(self, request: environments.UpdateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateEnvironmentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_update_user_workloads_config_map(self, request: environments.UpdateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_update_user_workloads_secret(self, request: environments.UpdateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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(EnvironmentsTransport): + """REST 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 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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or 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 _CreateEnvironment(EnvironmentsRestStub): + def __hash__(self): + return hash("CreateEnvironment") + + def __call__(self, + request: environments.CreateEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/environments', + 'body': 'environment', + }, + ] + request, metadata = self._interceptor.pre_create_environment(request, metadata) + pb_request = environments.CreateEnvironmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_environment(resp) + return resp + + class _CreateUserWorkloadsConfigMap(EnvironmentsRestStub): + def __hash__(self): + return hash("CreateUserWorkloadsConfigMap") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.CreateUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', + 'body': 'user_workloads_config_map', + }, + ] + request, metadata = self._interceptor.pre_create_user_workloads_config_map(request, metadata) + pb_request = environments.CreateUserWorkloadsConfigMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _CreateUserWorkloadsSecret(EnvironmentsRestStub): + def __hash__(self): + return hash("CreateUserWorkloadsSecret") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.CreateUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', + 'body': 'user_workloads_secret', + }, + ] + request, metadata = self._interceptor.pre_create_user_workloads_secret(request, metadata) + pb_request = environments.CreateUserWorkloadsSecretRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _DatabaseFailover(EnvironmentsRestStub): + def __hash__(self): + return hash("DatabaseFailover") + + def __call__(self, + request: environments.DatabaseFailoverRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:databaseFailover', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_database_failover(request, metadata) + pb_request = environments.DatabaseFailoverRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_database_failover(resp) + return resp + + class _DeleteEnvironment(EnvironmentsRestStub): + def __hash__(self): + return hash("DeleteEnvironment") + + def __call__(self, + request: environments.DeleteEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/environments/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_environment(request, metadata) + pb_request = environments.DeleteEnvironmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_environment(resp) + return resp + + class _DeleteUserWorkloadsConfigMap(EnvironmentsRestStub): + def __hash__(self): + return hash("DeleteUserWorkloadsConfigMap") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.DeleteUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_user_workloads_config_map(request, metadata) + pb_request = environments.DeleteUserWorkloadsConfigMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteUserWorkloadsSecret(EnvironmentsRestStub): + def __hash__(self): + return hash("DeleteUserWorkloadsSecret") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.DeleteUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_user_workloads_secret(request, metadata) + pb_request = environments.DeleteUserWorkloadsSecretRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _ExecuteAirflowCommand(EnvironmentsRestStub): + def __hash__(self): + return hash("ExecuteAirflowCommand") + + def __call__(self, + request: environments.ExecuteAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.ExecuteAirflowCommandResponse: + Response to + ExecuteAirflowCommandRequest. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:executeAirflowCommand', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_execute_airflow_command(request, metadata) + pb_request = environments.ExecuteAirflowCommandRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _FetchDatabaseProperties(EnvironmentsRestStub): + def __hash__(self): + return hash("FetchDatabaseProperties") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.FetchDatabasePropertiesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.FetchDatabasePropertiesResponse: + Response for + FetchDatabasePropertiesRequest. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:fetchDatabaseProperties', + }, + ] + request, metadata = self._interceptor.pre_fetch_database_properties(request, metadata) + pb_request = environments.FetchDatabasePropertiesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _GetEnvironment(EnvironmentsRestStub): + def __hash__(self): + return hash("GetEnvironment") + + def __call__(self, + request: environments.GetEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.Environment: + An environment for running + orchestration tasks. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/environments/*}', + }, + ] + request, metadata = self._interceptor.pre_get_environment(request, metadata) + pb_request = environments.GetEnvironmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _GetUserWorkloadsConfigMap(EnvironmentsRestStub): + def __hash__(self): + return hash("GetUserWorkloadsConfigMap") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.GetUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', + }, + ] + request, metadata = self._interceptor.pre_get_user_workloads_config_map(request, metadata) + pb_request = environments.GetUserWorkloadsConfigMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _GetUserWorkloadsSecret(EnvironmentsRestStub): + def __hash__(self): + return hash("GetUserWorkloadsSecret") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.GetUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', + }, + ] + request, metadata = self._interceptor.pre_get_user_workloads_secret(request, metadata) + pb_request = environments.GetUserWorkloadsSecretRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _ListEnvironments(EnvironmentsRestStub): + def __hash__(self): + return hash("ListEnvironments") + + def __call__(self, + request: environments.ListEnvironmentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.ListEnvironmentsResponse: + The environments in a project and + location. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/environments', + }, + ] + request, metadata = self._interceptor.pre_list_environments(request, metadata) + pb_request = environments.ListEnvironmentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _ListUserWorkloadsConfigMaps(EnvironmentsRestStub): + def __hash__(self): + return hash("ListUserWorkloadsConfigMaps") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.ListUserWorkloadsConfigMapsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.ListUserWorkloadsConfigMapsResponse: + The user workloads ConfigMaps for a + given environment. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', + }, + ] + request, metadata = self._interceptor.pre_list_user_workloads_config_maps(request, metadata) + pb_request = environments.ListUserWorkloadsConfigMapsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _ListUserWorkloadsSecrets(EnvironmentsRestStub): + def __hash__(self): + return hash("ListUserWorkloadsSecrets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.ListUserWorkloadsSecretsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.ListUserWorkloadsSecretsResponse: + The user workloads Secrets for a + given environment. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', + }, + ] + request, metadata = self._interceptor.pre_list_user_workloads_secrets(request, metadata) + pb_request = environments.ListUserWorkloadsSecretsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _ListWorkloads(EnvironmentsRestStub): + def __hash__(self): + return hash("ListWorkloads") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.ListWorkloadsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.ListWorkloadsResponse: + Response to ListWorkloadsRequest. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/environments/*}/workloads', + }, + ] + request, metadata = self._interceptor.pre_list_workloads(request, metadata) + pb_request = environments.ListWorkloadsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _LoadSnapshot(EnvironmentsRestStub): + def __hash__(self): + return hash("LoadSnapshot") + + def __call__(self, + request: environments.LoadSnapshotRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:loadSnapshot', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_load_snapshot(request, metadata) + pb_request = environments.LoadSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_load_snapshot(resp) + return resp + + class _PollAirflowCommand(EnvironmentsRestStub): + def __hash__(self): + return hash("PollAirflowCommand") + + def __call__(self, + request: environments.PollAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.PollAirflowCommandResponse: + Response to + PollAirflowCommandRequest. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:pollAirflowCommand', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_poll_airflow_command(request, metadata) + pb_request = environments.PollAirflowCommandRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _SaveSnapshot(EnvironmentsRestStub): + def __hash__(self): + return hash("SaveSnapshot") + + def __call__(self, + request: environments.SaveSnapshotRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:saveSnapshot', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_save_snapshot(request, metadata) + pb_request = environments.SaveSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_save_snapshot(resp) + return resp + + class _StopAirflowCommand(EnvironmentsRestStub): + def __hash__(self): + return hash("StopAirflowCommand") + + def __call__(self, + request: environments.StopAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.StopAirflowCommandResponse: + Response to + StopAirflowCommandRequest. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:stopAirflowCommand', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_stop_airflow_command(request, metadata) + pb_request = environments.StopAirflowCommandRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _UpdateEnvironment(EnvironmentsRestStub): + def __hash__(self): + return hash("UpdateEnvironment") + + def __call__(self, + request: environments.UpdateEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{name=projects/*/locations/*/environments/*}', + 'body': 'environment', + }, + ] + request, metadata = self._interceptor.pre_update_environment(request, metadata) + pb_request = environments.UpdateEnvironmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_environment(resp) + return resp + + class _UpdateUserWorkloadsConfigMap(EnvironmentsRestStub): + def __hash__(self): + return hash("UpdateUserWorkloadsConfigMap") + + def __call__(self, + request: environments.UpdateUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'put', + 'uri': '/v1/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', + 'body': 'user_workloads_config_map', + }, + ] + request, metadata = self._interceptor.pre_update_user_workloads_config_map(request, metadata) + pb_request = environments.UpdateUserWorkloadsConfigMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _UpdateUserWorkloadsSecret(EnvironmentsRestStub): + def __hash__(self): + return hash("UpdateUserWorkloadsSecret") + + def __call__(self, + request: environments.UpdateUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'put', + 'uri': '/v1/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', + 'body': 'user_workloads_secret', + }, + ] + request, metadata = self._interceptor.pre_update_user_workloads_secret(request, metadata) + pb_request = environments.UpdateUserWorkloadsSecretRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + @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(EnvironmentsRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(EnvironmentsRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(EnvironmentsRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'EnvironmentsRestTransport', +) 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..eb7f75b37afc --- /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,516 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 + + +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 = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) + + 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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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..cbe5f4ed7477 --- /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,863 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ImageVersionsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + ImageVersionsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 + + 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]] = ( + type(self).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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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..135e62df605c --- /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,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = image_versions.ListImageVersionsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = image_versions.ListImageVersionsRequest(request) + self._response = response + 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, 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/__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..2c4a6b349efb --- /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,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + ), + } + + 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..8020a7751752 --- /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,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.orchestration.airflow.service_v1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def 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..bb38a59a37cd --- /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,335 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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.grpc_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: gapic_v1.method_async.wrap_method( + self.list_image_versions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__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..ebf61bdd9e19 --- /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,533 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.orchestration.airflow.service_v1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore + +from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class 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, str]]) -> Tuple[image_versions.ListImageVersionsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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(ImageVersionsTransport): + """REST 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 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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + 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(ImageVersionsRestStub): + def __hash__(self): + return hash("ListImageVersions") + + def __call__(self, + request: image_versions.ListImageVersionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_versions.ListImageVersionsResponse: + The ImageVersions in a project and + location. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/imageVersions', + }, + ] + request, metadata = self._interceptor.pre_list_image_versions(request, metadata) + pb_request = image_versions.ListImageVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + 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(ImageVersionsRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(ImageVersionsRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(ImageVersionsRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ImageVersionsRestTransport', +) 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..f1c74173bd95 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.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 .environments import ( + 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__ = ( + '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..9d0a467d4cb0 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py @@ -0,0 +1,2969 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', + 'CheckUpgradeResponse', + 'DataRetentionConfig', + 'TaskLogsRetentionConfig', + }, +) + + +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/ + """ + + 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/ + """ + + 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): + The configuration settings for software + inside the environment. + node_config (google.cloud.orchestration.airflow.service_v1.types.NodeConfig): + The configuration used for the Kubernetes + Engine cluster. + private_environment_config (google.cloud.orchestration.airflow.service_v1.types.PrivateEnvironmentConfig): + 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 will be applied. The default + value is Saturday and Sunday 00-06 GMT. + 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): + 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-*.*.\* 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-*.*.\* 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-*.*.\* 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-*.*.\* 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-*.*.\* 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. + + 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): + 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): + 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. + 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, + ) + storage_config: 'StorageConfig' = proto.Field( + proto.MESSAGE, + number=9, + message='StorageConfig', + ) + + +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: + task_logs_retention_config (google.cloud.orchestration.airflow.service_v1.types.TaskLogsRetentionConfig): + Optional. The configuration settings for task + logs retention + """ + + 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. For details, see + go/composer-store-task-logs-in-cloud-logging-only-design-doc + """ + 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, + ) + + +__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..5e3cfb5f1101 --- /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" +] + +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.12" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/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"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/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('.') + # Remove once https://github.com/googleapis/python-api-core/pull/650 is merged + session.install("google-api-core>=2.19.1rc0") + 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_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..3fffc7af33c9 --- /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,3851 @@ +{ + "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.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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..dcf2905a8c0c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py @@ -0,0 +1,199 @@ +#! /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]] = { + '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..8f09d536771c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/setup.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-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.7.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /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.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 diff --git a/owl-bot-staging/google-cloud-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..473c24f0bdfa --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py @@ -0,0 +1,15930 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.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 + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateEnvironmentRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_create_environment_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateEnvironmentRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_environment in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_environment] = mock_object + + request = {} + await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_environment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=environments.CreateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_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, + ) + 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 + + +def test_get_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetEnvironmentRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_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, + )) + response = await client.get_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetEnvironmentRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_environment in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_environment] = mock_object + + request = {} + await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_environment_async(transport: str = 'grpc_asyncio', request_type=environments.GetEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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, + )) + 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 + + +@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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_environments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListEnvironmentsRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListEnvironmentsRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_environments in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_environments] = mock_object + + request = {} + await client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_environments_async(transport: str = 'grpc_asyncio', request_type=environments.ListEnvironmentsRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_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 = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_environments(request={}) + + assert pager._metadata == expected_metadata + + 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=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__', 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=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__', 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateEnvironmentRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_update_environment_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateEnvironmentRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_environment in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_environment] = mock_object + + request = {} + await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_environment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteEnvironmentRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_delete_environment_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteEnvironmentRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_environment in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_environment] = mock_object + + request = {} + await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_environment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_environment_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ExecuteAirflowCommandRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ExecuteAirflowCommandRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.execute_airflow_command in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.execute_airflow_command] = mock_object + + request = {} + await client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_execute_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.ExecuteAirflowCommandRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.StopAirflowCommandRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.StopAirflowCommandRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.stop_airflow_command in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.stop_airflow_command] = mock_object + + request = {} + await client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.StopAirflowCommandRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.PollAirflowCommandRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.PollAirflowCommandRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.poll_airflow_command in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.poll_airflow_command] = mock_object + + request = {} + await client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_poll_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.PollAirflowCommandRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workloads() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListWorkloadsRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListWorkloadsRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_workloads in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_workloads] = mock_object + + request = {} + await client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_workloads_async(transport: str = 'grpc_asyncio', request_type=environments.ListWorkloadsRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_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 = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workloads(request={}) + + assert pager._metadata == expected_metadata + + 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=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__', 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=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__', 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsSecretRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsSecretRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_user_workloads_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_user_workloads_secret] = mock_object + + request = {} + await client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsSecretRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsSecretRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_user_workloads_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_user_workloads_secret] = mock_object + + request = {} + await client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsSecretsRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsSecretsRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_user_workloads_secrets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_user_workloads_secrets] = mock_object + + request = {} + await client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_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 = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_user_workloads_secrets(request={}) + + assert pager._metadata == expected_metadata + + 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=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__', 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=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__', 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsSecretRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsSecretRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_user_workloads_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_user_workloads_secret] = mock_object + + request = {} + await client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsSecretRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsSecretRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_user_workloads_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_user_workloads_secret] = mock_object + + request = {} + await client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsConfigMapRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsConfigMapRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_user_workloads_config_map in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_user_workloads_config_map] = mock_object + + request = {} + await client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsConfigMapRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsConfigMapRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_user_workloads_config_map in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_user_workloads_config_map] = mock_object + + request = {} + await client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsConfigMapsRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsConfigMapsRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_user_workloads_config_maps in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_user_workloads_config_maps] = mock_object + + request = {} + await client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_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 = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_user_workloads_config_maps(request={}) + + assert pager._metadata == expected_metadata + + 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=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__', 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=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__', 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_user_workloads_config_map in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_user_workloads_config_map] = mock_object + + request = {} + await client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_user_workloads_config_map in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_user_workloads_config_map] = mock_object + + request = {} + await client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.save_snapshot() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.SaveSnapshotRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_save_snapshot_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.SaveSnapshotRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.save_snapshot in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.save_snapshot] = mock_object + + request = {} + await client.save_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.save_snapshot(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_save_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.SaveSnapshotRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.load_snapshot() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.LoadSnapshotRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_load_snapshot_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.LoadSnapshotRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.load_snapshot in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.load_snapshot] = mock_object + + request = {} + await client.load_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.load_snapshot(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_load_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.LoadSnapshotRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.database_failover() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DatabaseFailoverRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_database_failover_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DatabaseFailoverRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.database_failover in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.database_failover] = mock_object + + request = {} + await client.database_failover(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.database_failover(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_database_failover_async(transport: str = 'grpc_asyncio', request_type=environments.DatabaseFailoverRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.FetchDatabasePropertiesRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.fetch_database_properties in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.fetch_database_properties] = mock_object + + request = {} + await client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_fetch_database_properties_async(transport: str = 'grpc_asyncio', request_type=environments.FetchDatabasePropertiesRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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'] + + +@pytest.mark.parametrize("request_type", [ + environments.CreateEnvironmentRequest, + dict, +]) +def test_create_environment_rest(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': {'task_logs_retention_config': {'storage_mode': 1}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': 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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_environment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_create_environment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.CreateEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_environment_rest_bad_request(transport: str = 'rest', request_type=environments.CreateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_environment(request) + + +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 + + 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_create_environment_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetEnvironmentRequest, + dict, +]) +def test_get_environment_rest(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, + ) + + # 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 + 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 + +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 + + +@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, "pre_get_environment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.Environment.to_json(environments.Environment()) + + request = environments.GetEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.Environment() + + client.get_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_environment_rest_bad_request(transport: str = 'rest', request_type=environments.GetEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_environment(request) + + +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 + + 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_get_environment_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListEnvironmentsRequest, + dict, +]) +def test_list_environments_rest(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 = 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 + 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' + +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 + + +@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, "pre_list_environments") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.ListEnvironmentsResponse.to_json(environments.ListEnvironmentsResponse()) + + request = environments.ListEnvironmentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListEnvironmentsResponse() + + client.list_environments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_environments_rest_bad_request(transport: str = 'rest', request_type=environments.ListEnvironmentsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_environments(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateEnvironmentRequest, + dict, +]) +def test_update_environment_rest(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': {'task_logs_retention_config': {'storage_mode': 1}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': 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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_environment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_update_environment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.UpdateEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_environment_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_environment(request) + + +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 + + 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_update_environment_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteEnvironmentRequest, + dict, +]) +def test_delete_environment_rest(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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_environment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_delete_environment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.DeleteEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_environment_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_environment(request) + + +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 + + 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_delete_environment_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ExecuteAirflowCommandRequest, + dict, +]) +def test_execute_airflow_command_rest(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 = Response() + 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 + 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' + +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 + + +@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, "pre_execute_airflow_command") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.ExecuteAirflowCommandResponse.to_json(environments.ExecuteAirflowCommandResponse()) + + request = environments.ExecuteAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ExecuteAirflowCommandResponse() + + client.execute_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_execute_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.ExecuteAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.execute_airflow_command(request) + + +def test_execute_airflow_command_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.StopAirflowCommandRequest, + dict, +]) +def test_stop_airflow_command_rest(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 = Response() + 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 + 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'] + +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 + + +@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, "pre_stop_airflow_command") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.StopAirflowCommandResponse.to_json(environments.StopAirflowCommandResponse()) + + request = environments.StopAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.StopAirflowCommandResponse() + + client.stop_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.StopAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.stop_airflow_command(request) + + +def test_stop_airflow_command_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.PollAirflowCommandRequest, + dict, +]) +def test_poll_airflow_command_rest(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 = Response() + 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 + 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 + +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 + + +@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, "pre_poll_airflow_command") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.PollAirflowCommandResponse.to_json(environments.PollAirflowCommandResponse()) + + request = environments.PollAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.PollAirflowCommandResponse() + + client.poll_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_poll_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.PollAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.poll_airflow_command(request) + + +def test_poll_airflow_command_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListWorkloadsRequest, + dict, +]) +def test_list_workloads_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_list_workloads") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.ListWorkloadsResponse.to_json(environments.ListWorkloadsResponse()) + + request = environments.ListWorkloadsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListWorkloadsResponse() + + client.list_workloads(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workloads_rest_bad_request(transport: str = 'rest', request_type=environments.ListWorkloadsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_workloads(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsSecretRequest, + dict, +]) +def test_create_user_workloads_secret_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_create_user_workloads_secret") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + + request = environments.CreateUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + + client.create_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.CreateUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_user_workloads_secret(request) + + +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 + + 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_create_user_workloads_secret_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsSecretRequest, + dict, +]) +def test_get_user_workloads_secret_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_get_user_workloads_secret") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + + request = environments.GetUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + + client.get_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.GetUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_user_workloads_secret(request) + + +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 + + 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_get_user_workloads_secret_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsSecretsRequest, + dict, +]) +def test_list_user_workloads_secrets_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_list_user_workloads_secrets") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.ListUserWorkloadsSecretsResponse.to_json(environments.ListUserWorkloadsSecretsResponse()) + + request = environments.ListUserWorkloadsSecretsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListUserWorkloadsSecretsResponse() + + client.list_user_workloads_secrets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_user_workloads_secrets_rest_bad_request(transport: str = 'rest', request_type=environments.ListUserWorkloadsSecretsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_user_workloads_secrets(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateUserWorkloadsSecretRequest, + dict, +]) +def test_update_user_workloads_secret_rest(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 = 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 + 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' + +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 + + +@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, "pre_update_user_workloads_secret") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + + request = environments.UpdateUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + + client.update_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_user_workloads_secret(request) + + +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 + + 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_update_user_workloads_secret_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsSecretRequest, + dict, +]) +def test_delete_user_workloads_secret_rest(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 = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_user_workloads_secret(request) + + # Establish that the response is the type that we expect. + assert response is None + +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 + + 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", ))) + + +@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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + 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_delete_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_user_workloads_secret(request) + + +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 + + 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_delete_user_workloads_secret_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsConfigMapRequest, + dict, +]) +def test_create_user_workloads_config_map_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_create_user_workloads_config_map") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + + request = environments.CreateUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + + client.create_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.CreateUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_user_workloads_config_map(request) + + +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 + + 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_create_user_workloads_config_map_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsConfigMapRequest, + dict, +]) +def test_get_user_workloads_config_map_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_get_user_workloads_config_map") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + + request = environments.GetUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + + client.get_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.GetUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_user_workloads_config_map(request) + + +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 + + 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_get_user_workloads_config_map_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsConfigMapsRequest, + dict, +]) +def test_list_user_workloads_config_maps_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_list_user_workloads_config_maps") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.ListUserWorkloadsConfigMapsResponse.to_json(environments.ListUserWorkloadsConfigMapsResponse()) + + request = environments.ListUserWorkloadsConfigMapsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListUserWorkloadsConfigMapsResponse() + + client.list_user_workloads_config_maps(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_user_workloads_config_maps_rest_bad_request(transport: str = 'rest', request_type=environments.ListUserWorkloadsConfigMapsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_user_workloads_config_maps(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateUserWorkloadsConfigMapRequest, + dict, +]) +def test_update_user_workloads_config_map_rest(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 = 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 + 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' + +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 + + +@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, "pre_update_user_workloads_config_map") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + + request = environments.UpdateUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + + client.update_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_user_workloads_config_map(request) + + +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 + + 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_update_user_workloads_config_map_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsConfigMapRequest, + dict, +]) +def test_delete_user_workloads_config_map_rest(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 = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_user_workloads_config_map(request) + + # Establish that the response is the type that we expect. + assert response is None + +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 + + 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", ))) + + +@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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + 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_delete_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_user_workloads_config_map(request) + + +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 + + 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_delete_user_workloads_config_map_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.SaveSnapshotRequest, + dict, +]) +def test_save_snapshot_rest(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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.save_snapshot(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_save_snapshot") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.SaveSnapshotRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.save_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_save_snapshot_rest_bad_request(transport: str = 'rest', request_type=environments.SaveSnapshotRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.save_snapshot(request) + + +def test_save_snapshot_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.LoadSnapshotRequest, + dict, +]) +def test_load_snapshot_rest(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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.load_snapshot(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_load_snapshot") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.LoadSnapshotRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.load_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_load_snapshot_rest_bad_request(transport: str = 'rest', request_type=environments.LoadSnapshotRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.load_snapshot(request) + + +def test_load_snapshot_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DatabaseFailoverRequest, + dict, +]) +def test_database_failover_rest(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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.database_failover(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_database_failover") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.DatabaseFailoverRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.database_failover(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_database_failover_rest_bad_request(transport: str = 'rest', request_type=environments.DatabaseFailoverRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.database_failover(request) + + +def test_database_failover_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.FetchDatabasePropertiesRequest, + dict, +]) +def test_fetch_database_properties_rest(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 = 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 + 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 + +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 + + 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", ))) + + +@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, "pre_fetch_database_properties") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.FetchDatabasePropertiesResponse.to_json(environments.FetchDatabasePropertiesResponse()) + + request = environments.FetchDatabasePropertiesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.FetchDatabasePropertiesResponse() + + client.fetch_database_properties(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_database_properties_rest_bad_request(transport: str = 'rest', request_type=environments.FetchDatabasePropertiesRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.fetch_database_properties(request) + + +def test_fetch_database_properties_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = EnvironmentsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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', + '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) + + +def test_environments_rest_lro_client(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_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.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) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = 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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = 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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = 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..95050bfab6ec --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py @@ -0,0 +1,2739 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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.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 + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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("client_class,transport_class,transport_name", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_image_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == image_versions.ListImageVersionsRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ImageVersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == image_versions.ListImageVersionsRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_image_versions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_image_versions] = mock_object + + request = {} + await client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_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 = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_image_versions(request={}) + + assert pager._metadata == expected_metadata + + 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=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__', 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=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__', 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 + + +@pytest.mark.parametrize("request_type", [ + image_versions.ListImageVersionsRequest, + dict, +]) +def test_list_image_versions_rest(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 = 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 + 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' + +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 + + +@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, "pre_list_image_versions") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = image_versions.ListImageVersionsResponse.to_json(image_versions.ListImageVersionsResponse()) + + request = image_versions.ListImageVersionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = image_versions.ListImageVersionsResponse() + + client.list_image_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_image_versions_rest_bad_request(transport: str = 'rest', request_type=image_versions.ListImageVersionsRequest): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_image_versions(request) + + +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 + + 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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = ImageVersionsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ImageVersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = 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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = 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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = 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..5a08580483e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/README.rst @@ -0,0 +1,49 @@ +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 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..5c7ba31b939d --- /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..1fb16b4fa792 --- /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,3261 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 + + +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 = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) + + 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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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. + has_flattened_params = any([parent, environment]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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. + has_flattened_params = any([name, environment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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-3.\ *.*-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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, user_workloads_secret]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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, str]] = (), + ) -> 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-*.*.\* 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> pagers.ListUserWorkloadsSecretsAsyncPager: + r"""Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([user_workloads_secret]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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, str]] = (), + ) -> None: + r"""Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, user_workloads_config_map]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> pagers.ListUserWorkloadsConfigMapsAsyncPager: + r"""Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([user_workloads_config_map]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request 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, str]] = (), + ) -> None: + r"""Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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..2618a30bd48d --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py @@ -0,0 +1,3620 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = EnvironmentsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + EnvironmentsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 + + 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]] = ( + type(self).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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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. + has_flattened_params = any([parent, environment]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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. + has_flattened_params = any([name, environment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> 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-3.\ *.*-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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Creates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, user_workloads_secret]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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, str]] = (), + ) -> 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-*.*.\* 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> pagers.ListUserWorkloadsSecretsPager: + r"""Lists user workloads Secrets. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsSecret: + r"""Updates a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([user_workloads_secret]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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, str]] = (), + ) -> None: + r"""Deletes a user workloads Secret. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Creates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, user_workloads_config_map]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Gets an existing user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> pagers.ListUserWorkloadsConfigMapsPager: + r"""Lists user workloads ConfigMaps. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> environments.UserWorkloadsConfigMap: + r"""Updates a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([user_workloads_config_map]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request 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, str]] = (), + ) -> None: + r"""Deletes a user workloads ConfigMap. + + This method is supported for Cloud Composer environments in + versions composer-3.\ *.*-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_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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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..45f5dd2349b1 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py @@ -0,0 +1,502 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListEnvironmentsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListEnvironmentsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListWorkloadsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListWorkloadsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListUserWorkloadsSecretsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListUserWorkloadsSecretsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListUserWorkloadsConfigMapsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environments.ListUserWorkloadsConfigMapsRequest(request) + self._response = response + 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, 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/__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..6059007c51a1 --- /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,525 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + ), + } + + 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..f6eeb73c349c --- /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,1019 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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-3.\ *.*-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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def 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..5956a37637fc --- /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,1149 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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-3.\ *.*-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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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: gapic_v1.method_async.wrap_method( + self.create_environment, + default_timeout=None, + client_info=client_info, + ), + self.get_environment: gapic_v1.method_async.wrap_method( + self.get_environment, + default_timeout=None, + client_info=client_info, + ), + self.list_environments: gapic_v1.method_async.wrap_method( + self.list_environments, + default_timeout=None, + client_info=client_info, + ), + self.update_environment: gapic_v1.method_async.wrap_method( + self.update_environment, + default_timeout=None, + client_info=client_info, + ), + self.delete_environment: gapic_v1.method_async.wrap_method( + self.delete_environment, + default_timeout=None, + client_info=client_info, + ), + self.restart_web_server: gapic_v1.method_async.wrap_method( + self.restart_web_server, + default_timeout=None, + client_info=client_info, + ), + self.check_upgrade: gapic_v1.method_async.wrap_method( + self.check_upgrade, + default_timeout=None, + client_info=client_info, + ), + self.execute_airflow_command: gapic_v1.method_async.wrap_method( + self.execute_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.stop_airflow_command: gapic_v1.method_async.wrap_method( + self.stop_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.poll_airflow_command: gapic_v1.method_async.wrap_method( + self.poll_airflow_command, + default_timeout=None, + client_info=client_info, + ), + self.list_workloads: gapic_v1.method_async.wrap_method( + self.list_workloads, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_secret: gapic_v1.method_async.wrap_method( + self.create_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_secret: gapic_v1.method_async.wrap_method( + self.get_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_secrets: gapic_v1.method_async.wrap_method( + self.list_user_workloads_secrets, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_secret: gapic_v1.method_async.wrap_method( + self.update_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_secret: gapic_v1.method_async.wrap_method( + self.delete_user_workloads_secret, + default_timeout=None, + client_info=client_info, + ), + self.create_user_workloads_config_map: gapic_v1.method_async.wrap_method( + self.create_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.get_user_workloads_config_map: gapic_v1.method_async.wrap_method( + self.get_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.list_user_workloads_config_maps: gapic_v1.method_async.wrap_method( + self.list_user_workloads_config_maps, + default_timeout=None, + client_info=client_info, + ), + self.update_user_workloads_config_map: gapic_v1.method_async.wrap_method( + self.update_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.delete_user_workloads_config_map: gapic_v1.method_async.wrap_method( + self.delete_user_workloads_config_map, + default_timeout=None, + client_info=client_info, + ), + self.save_snapshot: gapic_v1.method_async.wrap_method( + self.save_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.load_snapshot: gapic_v1.method_async.wrap_method( + self.load_snapshot, + default_timeout=None, + client_info=client_info, + ), + self.database_failover: gapic_v1.method_async.wrap_method( + self.database_failover, + default_timeout=None, + client_info=client_info, + ), + self.fetch_database_properties: gapic_v1.method_async.wrap_method( + self.fetch_database_properties, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__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..6ebbe966b003 --- /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,3215 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +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 .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class 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, str]]) -> Tuple[environments.CheckUpgradeRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_create_environment(self, request: environments.CreateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateEnvironmentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_create_user_workloads_config_map(self, request: environments.CreateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_create_user_workloads_secret(self, request: environments.CreateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_database_failover(self, request: environments.DatabaseFailoverRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DatabaseFailoverRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_delete_environment(self, request: environments.DeleteEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DeleteEnvironmentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_delete_user_workloads_config_map(self, request: environments.DeleteUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DeleteUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[environments.DeleteUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[environments.ExecuteAirflowCommandRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_fetch_database_properties(self, request: environments.FetchDatabasePropertiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.FetchDatabasePropertiesRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_environment(self, request: environments.GetEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetEnvironmentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_user_workloads_config_map(self, request: environments.GetUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_user_workloads_secret(self, request: environments.GetUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_environments(self, request: environments.ListEnvironmentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListEnvironmentsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_user_workloads_config_maps(self, request: environments.ListUserWorkloadsConfigMapsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListUserWorkloadsConfigMapsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_user_workloads_secrets(self, request: environments.ListUserWorkloadsSecretsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListUserWorkloadsSecretsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_workloads(self, request: environments.ListWorkloadsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListWorkloadsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_load_snapshot(self, request: environments.LoadSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.LoadSnapshotRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_poll_airflow_command(self, request: environments.PollAirflowCommandRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.PollAirflowCommandRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_restart_web_server(self, request: environments.RestartWebServerRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.RestartWebServerRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_save_snapshot(self, request: environments.SaveSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.SaveSnapshotRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_stop_airflow_command(self, request: environments.StopAirflowCommandRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.StopAirflowCommandRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_update_environment(self, request: environments.UpdateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateEnvironmentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_update_user_workloads_config_map(self, request: environments.UpdateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_update_user_workloads_secret(self, request: environments.UpdateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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(EnvironmentsTransport): + """REST 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 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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or 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(EnvironmentsRestStub): + def __hash__(self): + return hash("CheckUpgrade") + + def __call__(self, + request: environments.CheckUpgradeRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:checkUpgrade', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_check_upgrade(request, metadata) + pb_request = environments.CheckUpgradeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_check_upgrade(resp) + return resp + + class _CreateEnvironment(EnvironmentsRestStub): + def __hash__(self): + return hash("CreateEnvironment") + + def __call__(self, + request: environments.CreateEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=projects/*/locations/*}/environments', + 'body': 'environment', + }, + ] + request, metadata = self._interceptor.pre_create_environment(request, metadata) + pb_request = environments.CreateEnvironmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_environment(resp) + return resp + + class _CreateUserWorkloadsConfigMap(EnvironmentsRestStub): + def __hash__(self): + return hash("CreateUserWorkloadsConfigMap") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.CreateUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', + 'body': 'user_workloads_config_map', + }, + ] + request, metadata = self._interceptor.pre_create_user_workloads_config_map(request, metadata) + pb_request = environments.CreateUserWorkloadsConfigMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _CreateUserWorkloadsSecret(EnvironmentsRestStub): + def __hash__(self): + return hash("CreateUserWorkloadsSecret") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.CreateUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', + 'body': 'user_workloads_secret', + }, + ] + request, metadata = self._interceptor.pre_create_user_workloads_secret(request, metadata) + pb_request = environments.CreateUserWorkloadsSecretRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _DatabaseFailover(EnvironmentsRestStub): + def __hash__(self): + return hash("DatabaseFailover") + + def __call__(self, + request: environments.DatabaseFailoverRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:databaseFailover', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_database_failover(request, metadata) + pb_request = environments.DatabaseFailoverRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_database_failover(resp) + return resp + + class _DeleteEnvironment(EnvironmentsRestStub): + def __hash__(self): + return hash("DeleteEnvironment") + + def __call__(self, + request: environments.DeleteEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_environment(request, metadata) + pb_request = environments.DeleteEnvironmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_environment(resp) + return resp + + class _DeleteUserWorkloadsConfigMap(EnvironmentsRestStub): + def __hash__(self): + return hash("DeleteUserWorkloadsConfigMap") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.DeleteUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_user_workloads_config_map(request, metadata) + pb_request = environments.DeleteUserWorkloadsConfigMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteUserWorkloadsSecret(EnvironmentsRestStub): + def __hash__(self): + return hash("DeleteUserWorkloadsSecret") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.DeleteUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_user_workloads_secret(request, metadata) + pb_request = environments.DeleteUserWorkloadsSecretRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _ExecuteAirflowCommand(EnvironmentsRestStub): + def __hash__(self): + return hash("ExecuteAirflowCommand") + + def __call__(self, + request: environments.ExecuteAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.ExecuteAirflowCommandResponse: + Response to + ExecuteAirflowCommandRequest. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:executeAirflowCommand', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_execute_airflow_command(request, metadata) + pb_request = environments.ExecuteAirflowCommandRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _FetchDatabaseProperties(EnvironmentsRestStub): + def __hash__(self): + return hash("FetchDatabaseProperties") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.FetchDatabasePropertiesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.FetchDatabasePropertiesResponse: + Response for + FetchDatabasePropertiesRequest. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:fetchDatabaseProperties', + }, + ] + request, metadata = self._interceptor.pre_fetch_database_properties(request, metadata) + pb_request = environments.FetchDatabasePropertiesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _GetEnvironment(EnvironmentsRestStub): + def __hash__(self): + return hash("GetEnvironment") + + def __call__(self, + request: environments.GetEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.Environment: + An environment for running + orchestration tasks. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*}', + }, + ] + request, metadata = self._interceptor.pre_get_environment(request, metadata) + pb_request = environments.GetEnvironmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _GetUserWorkloadsConfigMap(EnvironmentsRestStub): + def __hash__(self): + return hash("GetUserWorkloadsConfigMap") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.GetUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', + }, + ] + request, metadata = self._interceptor.pre_get_user_workloads_config_map(request, metadata) + pb_request = environments.GetUserWorkloadsConfigMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _GetUserWorkloadsSecret(EnvironmentsRestStub): + def __hash__(self): + return hash("GetUserWorkloadsSecret") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.GetUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', + }, + ] + request, metadata = self._interceptor.pre_get_user_workloads_secret(request, metadata) + pb_request = environments.GetUserWorkloadsSecretRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _ListEnvironments(EnvironmentsRestStub): + def __hash__(self): + return hash("ListEnvironments") + + def __call__(self, + request: environments.ListEnvironmentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.ListEnvironmentsResponse: + The environments in a project and + location. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*}/environments', + }, + ] + request, metadata = self._interceptor.pre_list_environments(request, metadata) + pb_request = environments.ListEnvironmentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _ListUserWorkloadsConfigMaps(EnvironmentsRestStub): + def __hash__(self): + return hash("ListUserWorkloadsConfigMaps") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.ListUserWorkloadsConfigMapsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.ListUserWorkloadsConfigMapsResponse: + The user workloads ConfigMaps for a + given environment. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', + }, + ] + request, metadata = self._interceptor.pre_list_user_workloads_config_maps(request, metadata) + pb_request = environments.ListUserWorkloadsConfigMapsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _ListUserWorkloadsSecrets(EnvironmentsRestStub): + def __hash__(self): + return hash("ListUserWorkloadsSecrets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.ListUserWorkloadsSecretsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.ListUserWorkloadsSecretsResponse: + The user workloads Secrets for a + given environment. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', + }, + ] + request, metadata = self._interceptor.pre_list_user_workloads_secrets(request, metadata) + pb_request = environments.ListUserWorkloadsSecretsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _ListWorkloads(EnvironmentsRestStub): + def __hash__(self): + return hash("ListWorkloads") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.ListWorkloadsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.ListWorkloadsResponse: + Response to ListWorkloadsRequest. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*/environments/*}/workloads', + }, + ] + request, metadata = self._interceptor.pre_list_workloads(request, metadata) + pb_request = environments.ListWorkloadsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _LoadSnapshot(EnvironmentsRestStub): + def __hash__(self): + return hash("LoadSnapshot") + + def __call__(self, + request: environments.LoadSnapshotRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:loadSnapshot', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_load_snapshot(request, metadata) + pb_request = environments.LoadSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_load_snapshot(resp) + return resp + + class _PollAirflowCommand(EnvironmentsRestStub): + def __hash__(self): + return hash("PollAirflowCommand") + + def __call__(self, + request: environments.PollAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.PollAirflowCommandResponse: + Response to + PollAirflowCommandRequest. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:pollAirflowCommand', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_poll_airflow_command(request, metadata) + pb_request = environments.PollAirflowCommandRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _RestartWebServer(EnvironmentsRestStub): + def __hash__(self): + return hash("RestartWebServer") + + def __call__(self, + request: environments.RestartWebServerRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*}:restartWebServer', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_restart_web_server(request, metadata) + pb_request = environments.RestartWebServerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_restart_web_server(resp) + return resp + + class _SaveSnapshot(EnvironmentsRestStub): + def __hash__(self): + return hash("SaveSnapshot") + + def __call__(self, + request: environments.SaveSnapshotRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:saveSnapshot', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_save_snapshot(request, metadata) + pb_request = environments.SaveSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_save_snapshot(resp) + return resp + + class _StopAirflowCommand(EnvironmentsRestStub): + def __hash__(self): + return hash("StopAirflowCommand") + + def __call__(self, + request: environments.StopAirflowCommandRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.StopAirflowCommandResponse: + Response to + StopAirflowCommandRequest. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:stopAirflowCommand', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_stop_airflow_command(request, metadata) + pb_request = environments.StopAirflowCommandRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _UpdateEnvironment(EnvironmentsRestStub): + def __hash__(self): + return hash("UpdateEnvironment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: environments.UpdateEnvironmentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*}', + 'body': 'environment', + }, + ] + request, metadata = self._interceptor.pre_update_environment(request, metadata) + pb_request = environments.UpdateEnvironmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_environment(resp) + return resp + + class _UpdateUserWorkloadsConfigMap(EnvironmentsRestStub): + def __hash__(self): + return hash("UpdateUserWorkloadsConfigMap") + + def __call__(self, + request: environments.UpdateUserWorkloadsConfigMapRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsConfigMap: + User workloads ConfigMap used by + Airflow tasks that run with Kubernetes + executor or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'put', + 'uri': '/v1beta1/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', + 'body': 'user_workloads_config_map', + }, + ] + request, metadata = self._interceptor.pre_update_user_workloads_config_map(request, metadata) + pb_request = environments.UpdateUserWorkloadsConfigMapRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + return resp + + class _UpdateUserWorkloadsSecret(EnvironmentsRestStub): + def __hash__(self): + return hash("UpdateUserWorkloadsSecret") + + def __call__(self, + request: environments.UpdateUserWorkloadsSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.environments.UserWorkloadsSecret: + User workloads Secret used by Airflow + tasks that run with Kubernetes executor + or KubernetesPodOperator. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'put', + 'uri': '/v1beta1/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', + 'body': 'user_workloads_secret', + }, + ] + request, metadata = self._interceptor.pre_update_user_workloads_secret(request, metadata) + pb_request = environments.UpdateUserWorkloadsSecretRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + 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(EnvironmentsRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(EnvironmentsRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(EnvironmentsRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'EnvironmentsRestTransport', +) 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..bedf994089db --- /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,516 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 + + +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 = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) + + 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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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..ed14e2e66caa --- /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,863 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.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 + +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 + + @staticmethod + def _compare_universes(client_universe: str, + credentials: ga_credentials.Credentials) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ImageVersionsClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError("The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default.") + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = (self._is_universe_domain_valid or + ImageVersionsClient._compare_universes(self.universe_domain, self.transport._credentials)) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 + + 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]] = ( + type(self).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, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, 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, + 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, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # 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..edf23d8c6f79 --- /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,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = image_versions.ListImageVersionsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest): + The initial request object. + response (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = image_versions.ListImageVersionsRequest(request) + self._response = response + 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, 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/__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..32089ad848d8 --- /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,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + ), + } + + 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..fb20b510e423 --- /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,325 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore +from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def 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..8d8dda7560a5 --- /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,335 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.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 + + +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), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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.grpc_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: gapic_v1.method_async.wrap_method( + self.list_image_versions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__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..eb609417c796 --- /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,533 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions +from google.longrunning import operations_pb2 # type: ignore + +from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class 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, str]]) -> Tuple[image_versions.ListImageVersionsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the 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(ImageVersionsTransport): + """REST 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 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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + 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(ImageVersionsRestStub): + def __hash__(self): + return hash("ListImageVersions") + + def __call__(self, + request: image_versions.ListImageVersionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_versions.ListImageVersionsResponse: + The ImageVersions in a project and + location. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*}/imageVersions', + }, + ] + request, metadata = self._interceptor.pre_list_image_versions(request, metadata) + pb_request = image_versions.ListImageVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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) + 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(ImageVersionsRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(ImageVersionsRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(ImageVersionsRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ImageVersionsRestTransport', +) 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..54f4f24cc1a2 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py @@ -0,0 +1,3146 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/ + """ + + 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/ + """ + + 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): + The configuration settings for software + inside the environment. + node_config (google.cloud.orchestration.airflow.service_v1beta1.types.NodeConfig): + The configuration used for the Kubernetes + Engine cluster. + private_environment_config (google.cloud.orchestration.airflow.service_v1beta1.types.PrivateEnvironmentConfig): + 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): + 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-*.*.\* 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-*.*.\* 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-*.*.\* 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-*.*.\* 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-*.*.\* 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-*.*.\* 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): + 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): + 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. + 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, + ) + 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..020f6ffc86cb --- /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" +] + +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.12" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/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"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/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('.') + # Remove once https://github.com/googleapis/python-api-core/pull/650 is merged + session.install("google-api-core>=2.19.1rc0") + 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..4c413d500bdb --- /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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..d6d51f4e7b2b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/setup.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-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.7.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /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.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 diff --git a/owl-bot-staging/google-cloud-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..6efeb82b0506 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py @@ -0,0 +1,16831 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.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 + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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("client_class,transport_class,transport_name", [ + (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), + (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateEnvironmentRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_create_environment_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateEnvironmentRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_environment in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_environment] = mock_object + + request = {} + await client.create_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_environment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=environments.CreateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_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, + ) + 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 + + +def test_get_environment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetEnvironmentRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_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, + )) + response = await client.get_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetEnvironmentRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_environment in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_environment] = mock_object + + request = {} + await client.get_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_environment_async(transport: str = 'grpc_asyncio', request_type=environments.GetEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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, + )) + 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 + + +@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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_environments), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_environments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListEnvironmentsRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListEnvironmentsRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_environments in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_environments] = mock_object + + request = {} + await client.list_environments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_environments_async(transport: str = 'grpc_asyncio', request_type=environments.ListEnvironmentsRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_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 = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_environments(request={}) + + assert pager._metadata == expected_metadata + + 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=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__', 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=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__', 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateEnvironmentRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_update_environment_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateEnvironmentRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_environment in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_environment] = mock_object + + request = {} + await client.update_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_environment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteEnvironmentRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_delete_environment_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteEnvironmentRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_environment in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_environment] = mock_object + + request = {} + await client.delete_environment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_environment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_environment_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteEnvironmentRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.RestartWebServerRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_restart_web_server_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.RestartWebServerRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.restart_web_server in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.restart_web_server] = mock_object + + request = {} + await client.restart_web_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.restart_web_server(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_restart_web_server_async(transport: str = 'grpc_asyncio', request_type=environments.RestartWebServerRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.check_upgrade), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.check_upgrade() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CheckUpgradeRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_check_upgrade_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CheckUpgradeRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.check_upgrade in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.check_upgrade] = mock_object + + request = {} + await client.check_upgrade(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.check_upgrade(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_check_upgrade_async(transport: str = 'grpc_asyncio', request_type=environments.CheckUpgradeRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ExecuteAirflowCommandRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ExecuteAirflowCommandRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.execute_airflow_command in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.execute_airflow_command] = mock_object + + request = {} + await client.execute_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_execute_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.ExecuteAirflowCommandRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.StopAirflowCommandRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.StopAirflowCommandRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.stop_airflow_command in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.stop_airflow_command] = mock_object + + request = {} + await client.stop_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_stop_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.StopAirflowCommandRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.PollAirflowCommandRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.PollAirflowCommandRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.poll_airflow_command in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.poll_airflow_command] = mock_object + + request = {} + await client.poll_airflow_command(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_poll_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.PollAirflowCommandRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_workloads() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListWorkloadsRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListWorkloadsRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_workloads in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_workloads] = mock_object + + request = {} + await client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_workloads_async(transport: str = 'grpc_asyncio', request_type=environments.ListWorkloadsRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_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 = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_workloads(request={}) + + assert pager._metadata == expected_metadata + + 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=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__', 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=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__', 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsSecretRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsSecretRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_user_workloads_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_user_workloads_secret] = mock_object + + request = {} + await client.create_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsSecretRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsSecretRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_user_workloads_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_user_workloads_secret] = mock_object + + request = {} + await client.get_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsSecretsRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsSecretsRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_user_workloads_secrets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_user_workloads_secrets] = mock_object + + request = {} + await client.list_user_workloads_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_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 = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_user_workloads_secrets(request={}) + + assert pager._metadata == expected_metadata + + 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=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__', 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=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__', 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsSecretRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsSecretRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_user_workloads_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_user_workloads_secret] = mock_object + + request = {} + await client.update_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsSecretRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsSecretRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_user_workloads_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_user_workloads_secret] = mock_object + + request = {} + await client.delete_user_workloads_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsConfigMapRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.CreateUserWorkloadsConfigMapRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_user_workloads_config_map in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_user_workloads_config_map] = mock_object + + request = {} + await client.create_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsConfigMapRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.GetUserWorkloadsConfigMapRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_user_workloads_config_map in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_user_workloads_config_map] = mock_object + + request = {} + await client.get_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsConfigMapsRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.ListUserWorkloadsConfigMapsRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_user_workloads_config_maps in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_user_workloads_config_maps] = mock_object + + request = {} + await client.list_user_workloads_config_maps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_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 = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_user_workloads_config_maps(request={}) + + assert pager._metadata == expected_metadata + + 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=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__', 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=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__', 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_user_workloads_config_map in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_user_workloads_config_map] = mock_object + + request = {} + await client.update_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_user_workloads_config_map in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_user_workloads_config_map] = mock_object + + request = {} + await client.delete_user_workloads_config_map(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.save_snapshot), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.save_snapshot() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.SaveSnapshotRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_save_snapshot_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.SaveSnapshotRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.save_snapshot in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.save_snapshot] = mock_object + + request = {} + await client.save_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.save_snapshot(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_save_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.SaveSnapshotRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.load_snapshot), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.load_snapshot() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.LoadSnapshotRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_load_snapshot_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.LoadSnapshotRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.load_snapshot in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.load_snapshot] = mock_object + + request = {} + await client.load_snapshot(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.load_snapshot(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_load_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.LoadSnapshotRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.database_failover), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.database_failover() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DatabaseFailoverRequest() + + +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 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 + +@pytest.mark.asyncio +async def test_database_failover_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.DatabaseFailoverRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.database_failover in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.database_failover] = mock_object + + request = {} + await client.database_failover(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.database_failover(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_database_failover_async(transport: str = 'grpc_asyncio', request_type=environments.DatabaseFailoverRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environments.FetchDatabasePropertiesRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.fetch_database_properties in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.fetch_database_properties] = mock_object + + request = {} + await client.fetch_database_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.call_count == 2 + +@pytest.mark.asyncio +async def test_fetch_database_properties_async(transport: str = 'grpc_asyncio', request_type=environments.FetchDatabasePropertiesRequest): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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'] + + +@pytest.mark.parametrize("request_type", [ + environments.CreateEnvironmentRequest, + dict, +]) +def test_create_environment_rest(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, '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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_environment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_create_environment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.CreateEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_environment_rest_bad_request(transport: str = 'rest', request_type=environments.CreateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_environment(request) + + +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 + + 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_create_environment_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetEnvironmentRequest, + dict, +]) +def test_get_environment_rest(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, + ) + + # 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 + 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 + +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 + + +@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, "pre_get_environment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.Environment.to_json(environments.Environment()) + + request = environments.GetEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.Environment() + + client.get_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_environment_rest_bad_request(transport: str = 'rest', request_type=environments.GetEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_environment(request) + + +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 + + 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_get_environment_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListEnvironmentsRequest, + dict, +]) +def test_list_environments_rest(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 = 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 + 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' + +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 + + +@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, "pre_list_environments") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.ListEnvironmentsResponse.to_json(environments.ListEnvironmentsResponse()) + + request = environments.ListEnvironmentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListEnvironmentsResponse() + + client.list_environments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_environments_rest_bad_request(transport: str = 'rest', request_type=environments.ListEnvironmentsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_environments(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateEnvironmentRequest, + dict, +]) +def test_update_environment_rest(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, '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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_environment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + 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", ))) + + +@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, "pre_update_environment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.UpdateEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_environment_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_environment(request) + + +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 + + 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_update_environment_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteEnvironmentRequest, + dict, +]) +def test_delete_environment_rest(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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_environment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_delete_environment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.DeleteEnvironmentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_environment_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteEnvironmentRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_environment(request) + + +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 + + 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_delete_environment_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.RestartWebServerRequest, + dict, +]) +def test_restart_web_server_rest(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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.restart_web_server(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_restart_web_server") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.RestartWebServerRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restart_web_server(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restart_web_server_rest_bad_request(transport: str = 'rest', request_type=environments.RestartWebServerRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.restart_web_server(request) + + +def test_restart_web_server_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.CheckUpgradeRequest, + dict, +]) +def test_check_upgrade_rest(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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.check_upgrade(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_check_upgrade") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.CheckUpgradeRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.check_upgrade(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_check_upgrade_rest_bad_request(transport: str = 'rest', request_type=environments.CheckUpgradeRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.check_upgrade(request) + + +def test_check_upgrade_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ExecuteAirflowCommandRequest, + dict, +]) +def test_execute_airflow_command_rest(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 = Response() + 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 + 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' + +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 + + +@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, "pre_execute_airflow_command") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.ExecuteAirflowCommandResponse.to_json(environments.ExecuteAirflowCommandResponse()) + + request = environments.ExecuteAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ExecuteAirflowCommandResponse() + + client.execute_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_execute_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.ExecuteAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.execute_airflow_command(request) + + +def test_execute_airflow_command_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.StopAirflowCommandRequest, + dict, +]) +def test_stop_airflow_command_rest(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 = Response() + 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 + 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'] + +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 + + +@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, "pre_stop_airflow_command") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.StopAirflowCommandResponse.to_json(environments.StopAirflowCommandResponse()) + + request = environments.StopAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.StopAirflowCommandResponse() + + client.stop_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.StopAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.stop_airflow_command(request) + + +def test_stop_airflow_command_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.PollAirflowCommandRequest, + dict, +]) +def test_poll_airflow_command_rest(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 = Response() + 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 + 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 + +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 + + +@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, "pre_poll_airflow_command") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.PollAirflowCommandResponse.to_json(environments.PollAirflowCommandResponse()) + + request = environments.PollAirflowCommandRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.PollAirflowCommandResponse() + + client.poll_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_poll_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.PollAirflowCommandRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.poll_airflow_command(request) + + +def test_poll_airflow_command_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListWorkloadsRequest, + dict, +]) +def test_list_workloads_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_list_workloads") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.ListWorkloadsResponse.to_json(environments.ListWorkloadsResponse()) + + request = environments.ListWorkloadsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListWorkloadsResponse() + + client.list_workloads(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workloads_rest_bad_request(transport: str = 'rest', request_type=environments.ListWorkloadsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_workloads(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsSecretRequest, + dict, +]) +def test_create_user_workloads_secret_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_create_user_workloads_secret") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + + request = environments.CreateUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + + client.create_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.CreateUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_user_workloads_secret(request) + + +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 + + 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_create_user_workloads_secret_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsSecretRequest, + dict, +]) +def test_get_user_workloads_secret_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_get_user_workloads_secret") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + + request = environments.GetUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + + client.get_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.GetUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_user_workloads_secret(request) + + +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 + + 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_get_user_workloads_secret_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsSecretsRequest, + dict, +]) +def test_list_user_workloads_secrets_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_list_user_workloads_secrets") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.ListUserWorkloadsSecretsResponse.to_json(environments.ListUserWorkloadsSecretsResponse()) + + request = environments.ListUserWorkloadsSecretsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListUserWorkloadsSecretsResponse() + + client.list_user_workloads_secrets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_user_workloads_secrets_rest_bad_request(transport: str = 'rest', request_type=environments.ListUserWorkloadsSecretsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_user_workloads_secrets(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateUserWorkloadsSecretRequest, + dict, +]) +def test_update_user_workloads_secret_rest(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 = 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 + 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' + +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 + + +@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, "pre_update_user_workloads_secret") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) + + request = environments.UpdateUserWorkloadsSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsSecret() + + client.update_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_user_workloads_secret(request) + + +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 + + 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_update_user_workloads_secret_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsSecretRequest, + dict, +]) +def test_delete_user_workloads_secret_rest(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 = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_user_workloads_secret(request) + + # Establish that the response is the type that we expect. + assert response is None + +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 + + 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", ))) + + +@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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + 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_delete_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteUserWorkloadsSecretRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_user_workloads_secret(request) + + +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 + + 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_delete_user_workloads_secret_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.CreateUserWorkloadsConfigMapRequest, + dict, +]) +def test_create_user_workloads_config_map_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_create_user_workloads_config_map") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + + request = environments.CreateUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + + client.create_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.CreateUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_user_workloads_config_map(request) + + +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 + + 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_create_user_workloads_config_map_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.GetUserWorkloadsConfigMapRequest, + dict, +]) +def test_get_user_workloads_config_map_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_get_user_workloads_config_map") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + + request = environments.GetUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + + client.get_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.GetUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_user_workloads_config_map(request) + + +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 + + 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_get_user_workloads_config_map_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.ListUserWorkloadsConfigMapsRequest, + dict, +]) +def test_list_user_workloads_config_maps_rest(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 = 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 + 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' + +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 + + 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", ))) + + +@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, "pre_list_user_workloads_config_maps") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.ListUserWorkloadsConfigMapsResponse.to_json(environments.ListUserWorkloadsConfigMapsResponse()) + + request = environments.ListUserWorkloadsConfigMapsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.ListUserWorkloadsConfigMapsResponse() + + client.list_user_workloads_config_maps(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_user_workloads_config_maps_rest_bad_request(transport: str = 'rest', request_type=environments.ListUserWorkloadsConfigMapsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_user_workloads_config_maps(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + environments.UpdateUserWorkloadsConfigMapRequest, + dict, +]) +def test_update_user_workloads_config_map_rest(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 = 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 + 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' + +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 + + +@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, "pre_update_user_workloads_config_map") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) + + request = environments.UpdateUserWorkloadsConfigMapRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.UserWorkloadsConfigMap() + + client.update_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_user_workloads_config_map(request) + + +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 + + 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_update_user_workloads_config_map_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DeleteUserWorkloadsConfigMapRequest, + dict, +]) +def test_delete_user_workloads_config_map_rest(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 = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_user_workloads_config_map(request) + + # Establish that the response is the type that we expect. + assert response is None + +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 + + 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", ))) + + +@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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + 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_delete_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteUserWorkloadsConfigMapRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_user_workloads_config_map(request) + + +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 + + 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_delete_user_workloads_config_map_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.SaveSnapshotRequest, + dict, +]) +def test_save_snapshot_rest(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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.save_snapshot(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_save_snapshot") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.SaveSnapshotRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.save_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_save_snapshot_rest_bad_request(transport: str = 'rest', request_type=environments.SaveSnapshotRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.save_snapshot(request) + + +def test_save_snapshot_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.LoadSnapshotRequest, + dict, +]) +def test_load_snapshot_rest(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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.load_snapshot(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_load_snapshot") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.LoadSnapshotRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.load_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_load_snapshot_rest_bad_request(transport: str = 'rest', request_type=environments.LoadSnapshotRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.load_snapshot(request) + + +def test_load_snapshot_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.DatabaseFailoverRequest, + dict, +]) +def test_database_failover_rest(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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.database_failover(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + +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 + + +@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, "pre_database_failover") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = environments.DatabaseFailoverRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.database_failover(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_database_failover_rest_bad_request(transport: str = 'rest', request_type=environments.DatabaseFailoverRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.database_failover(request) + + +def test_database_failover_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + environments.FetchDatabasePropertiesRequest, + dict, +]) +def test_fetch_database_properties_rest(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 = 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 + 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 + +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 + + 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", ))) + + +@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, "pre_fetch_database_properties") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = environments.FetchDatabasePropertiesResponse.to_json(environments.FetchDatabasePropertiesResponse()) + + request = environments.FetchDatabasePropertiesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = environments.FetchDatabasePropertiesResponse() + + client.fetch_database_properties(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_database_properties_rest_bad_request(transport: str = 'rest', request_type=environments.FetchDatabasePropertiesRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.fetch_database_properties(request) + + +def test_fetch_database_properties_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = EnvironmentsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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) + + +def test_environments_rest_lro_client(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_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) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = 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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = 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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = 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..c69b17a0f398 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py @@ -0,0 +1,2739 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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.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 + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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("client_class,transport_class,transport_name", [ + (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), + (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), +]) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + transport=transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class( + transport=transport_class(credentials=credentials) + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize("client_class,transport_name", [ + (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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_image_versions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_image_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == image_versions.ListImageVersionsRequest() + + +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_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ImageVersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_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() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == image_versions.ListImageVersionsRequest() + +@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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_image_versions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_image_versions] = mock_object + + request = {} + await client.list_image_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_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 = () + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_image_versions(request={}) + + assert pager._metadata == expected_metadata + + 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=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__', 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=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__', 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 + + +@pytest.mark.parametrize("request_type", [ + image_versions.ListImageVersionsRequest, + dict, +]) +def test_list_image_versions_rest(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 = 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 + 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' + +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 + + +@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, "pre_list_image_versions") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = image_versions.ListImageVersionsResponse.to_json(image_versions.ListImageVersionsResponse()) + + request = image_versions.ListImageVersionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = image_versions.ListImageVersionsResponse() + + client.list_image_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_image_versions_rest_bad_request(transport: str = 'rest', request_type=image_versions.ListImageVersionsRequest): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_image_versions(request) + + +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 + + 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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = ImageVersionsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ImageVersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = 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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = 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=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ImageVersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = 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 fee4ff8858511c825347eb6ed3c750d260ed6971 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 10 Jul 2024 03:56:41 +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 | 49 - .../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 | 155 - .../airflow/service/gapic_version.py | 16 - .../orchestration/airflow/service/py.typed | 2 - .../airflow/service_v1/__init__.py | 156 - .../airflow/service_v1/gapic_metadata.json | 407 - .../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 | 3029 --- .../services/environments/client.py | 3388 ---- .../services/environments/pagers.py | 502 - .../environments/transports/__init__.py | 38 - .../services/environments/transports/base.py | 497 - .../services/environments/transports/grpc.py | 964 - .../environments/transports/grpc_asyncio.py | 1084 - .../services/environments/transports/rest.py | 2986 --- .../services/image_versions/__init__.py | 22 - .../services/image_versions/async_client.py | 516 - .../services/image_versions/client.py | 863 - .../services/image_versions/pagers.py | 139 - .../image_versions/transports/__init__.py | 38 - .../image_versions/transports/base.py | 182 - .../image_versions/transports/grpc.py | 325 - .../image_versions/transports/grpc_asyncio.py | 335 - .../image_versions/transports/rest.py | 533 - .../airflow/service_v1/types/__init__.py | 148 - .../airflow/service_v1/types/environments.py | 2969 --- .../service_v1/types/image_versions.py | 148 - .../airflow/service_v1/types/operations.py | 147 - .../v1/mypy.ini | 3 - .../v1/noxfile.py | 280 - ...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 | 3851 ---- .../v1/scripts/fixup_service_v1_keywords.py | 199 - .../v1/setup.py | 93 - .../v1/testing/constraints-3.10.txt | 6 - .../v1/testing/constraints-3.11.txt | 6 - .../v1/testing/constraints-3.12.txt | 6 - .../v1/testing/constraints-3.7.txt | 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 | 15930 --------------- .../gapic/service_v1/test_image_versions.py | 2739 --- .../v1beta1/.coveragerc | 13 - .../v1beta1/.flake8 | 33 - .../v1beta1/MANIFEST.in | 2 - .../v1beta1/README.rst | 49 - .../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 | 3261 --- .../services/environments/client.py | 3620 ---- .../services/environments/pagers.py | 502 - .../environments/transports/__init__.py | 38 - .../services/environments/transports/base.py | 525 - .../services/environments/transports/grpc.py | 1019 - .../environments/transports/grpc_asyncio.py | 1149 -- .../services/environments/transports/rest.py | 3215 --- .../services/image_versions/__init__.py | 22 - .../services/image_versions/async_client.py | 516 - .../services/image_versions/client.py | 863 - .../services/image_versions/pagers.py | 139 - .../image_versions/transports/__init__.py | 38 - .../image_versions/transports/base.py | 182 - .../image_versions/transports/grpc.py | 325 - .../image_versions/transports/grpc_asyncio.py | 335 - .../image_versions/transports/rest.py | 533 - .../airflow/service_v1beta1/types/__init__.py | 154 - .../service_v1beta1/types/environments.py | 3146 --- .../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 | 93 - .../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.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 | 16831 ---------------- .../service_v1beta1/test_image_versions.py | 2739 --- .../airflow/service/gapic_version.py | 2 +- .../airflow/service_v1/gapic_version.py | 2 +- .../airflow/service_v1beta1/__init__.py | 2 + .../airflow/service_v1beta1/gapic_version.py | 2 +- .../airflow/service_v1beta1/types/__init__.py | 2 + .../service_v1beta1/types/environments.py | 74 +- ...loud.orchestration.airflow.service.v1.json | 2 +- ...orchestration.airflow.service.v1beta1.json | 2 +- .../service_v1beta1/test_environments.py | 14 +- 225 files changed, 90 insertions(+), 94257 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/__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/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/__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/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_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.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/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/__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/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/__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/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.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 5a08580483e9..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/README.rst +++ /dev/null @@ -1,49 +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 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 135df39e1f89..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 ed870605e81d..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py +++ /dev/null @@ -1,155 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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', - '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 9a4c18f2b473..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py +++ /dev/null @@ -1,156 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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', -'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 3511b1f8d28f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json +++ /dev/null @@ -1,407 +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": { - "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": { - "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": { - "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 e10a84931fc2..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py +++ /dev/null @@ -1,3029 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 - - -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 = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) - - 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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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. - has_flattened_params = any([parent, environment]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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. - has_flattened_params = any([name, environment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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-3.\ *.*-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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, user_workloads_secret]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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, str]] = (), - ) -> 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-*.*.\* 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> pagers.ListUserWorkloadsSecretsAsyncPager: - r"""Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([user_workloads_secret]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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, str]] = (), - ) -> None: - r"""Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, user_workloads_config_map]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> pagers.ListUserWorkloadsConfigMapsAsyncPager: - r"""Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([user_workloads_config_map]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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, str]] = (), - ) -> None: - r"""Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 a66975dbf31a..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py +++ /dev/null @@ -1,3388 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = EnvironmentsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - EnvironmentsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 - - 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]] = ( - type(self).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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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. - has_flattened_params = any([parent, environment]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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. - has_flattened_params = any([name, environment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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-3.\ *.*-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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, user_workloads_secret]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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, str]] = (), - ) -> 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-*.*.\* 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> pagers.ListUserWorkloadsSecretsPager: - r"""Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([user_workloads_secret]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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, str]] = (), - ) -> None: - r"""Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, user_workloads_config_map]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> pagers.ListUserWorkloadsConfigMapsPager: - r"""Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([user_workloads_config_map]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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, str]] = (), - ) -> None: - r"""Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 38e83b47dd71..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py +++ /dev/null @@ -1,502 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListEnvironmentsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListEnvironmentsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListEnvironmentsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListWorkloadsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListWorkloadsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListWorkloadsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListUserWorkloadsSecretsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsSecretsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListUserWorkloadsSecretsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListUserWorkloadsConfigMapsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListUserWorkloadsConfigMapsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListUserWorkloadsConfigMapsRequest(request) - self._response = response - 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, 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/__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 de3645dacc12..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py +++ /dev/null @@ -1,497 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.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, - ), - } - - 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 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 a16685f661fd..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py +++ /dev/null @@ -1,964 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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-3.\ *.*-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.grpc_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 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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def 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 7c60dac84081..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,1084 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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-3.\ *.*-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.grpc_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 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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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: gapic_v1.method_async.wrap_method( - self.create_environment, - default_timeout=None, - client_info=client_info, - ), - self.get_environment: gapic_v1.method_async.wrap_method( - self.get_environment, - default_timeout=None, - client_info=client_info, - ), - self.list_environments: gapic_v1.method_async.wrap_method( - self.list_environments, - default_timeout=None, - client_info=client_info, - ), - self.update_environment: gapic_v1.method_async.wrap_method( - self.update_environment, - default_timeout=None, - client_info=client_info, - ), - self.delete_environment: gapic_v1.method_async.wrap_method( - self.delete_environment, - default_timeout=None, - client_info=client_info, - ), - self.execute_airflow_command: gapic_v1.method_async.wrap_method( - self.execute_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.stop_airflow_command: gapic_v1.method_async.wrap_method( - self.stop_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.poll_airflow_command: gapic_v1.method_async.wrap_method( - self.poll_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.list_workloads: gapic_v1.method_async.wrap_method( - self.list_workloads, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_secret: gapic_v1.method_async.wrap_method( - self.create_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_secret: gapic_v1.method_async.wrap_method( - self.get_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_secrets: gapic_v1.method_async.wrap_method( - self.list_user_workloads_secrets, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_secret: gapic_v1.method_async.wrap_method( - self.update_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_secret: gapic_v1.method_async.wrap_method( - self.delete_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_config_map: gapic_v1.method_async.wrap_method( - self.create_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_config_map: gapic_v1.method_async.wrap_method( - self.get_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_config_maps: gapic_v1.method_async.wrap_method( - self.list_user_workloads_config_maps, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_config_map: gapic_v1.method_async.wrap_method( - self.update_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_config_map: gapic_v1.method_async.wrap_method( - self.delete_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.save_snapshot: gapic_v1.method_async.wrap_method( - self.save_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.load_snapshot: gapic_v1.method_async.wrap_method( - self.load_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.database_failover: gapic_v1.method_async.wrap_method( - self.database_failover, - default_timeout=None, - client_info=client_info, - ), - self.fetch_database_properties: gapic_v1.method_async.wrap_method( - self.fetch_database_properties, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__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 03635a58f280..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py +++ /dev/null @@ -1,2986 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -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 .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class 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_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_create_environment(self, request: environments.CreateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateEnvironmentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_create_user_workloads_config_map(self, request: environments.CreateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_create_user_workloads_secret(self, request: environments.CreateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_database_failover(self, request: environments.DatabaseFailoverRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DatabaseFailoverRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_delete_environment(self, request: environments.DeleteEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DeleteEnvironmentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_delete_user_workloads_config_map(self, request: environments.DeleteUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DeleteUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[environments.DeleteUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[environments.ExecuteAirflowCommandRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_fetch_database_properties(self, request: environments.FetchDatabasePropertiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.FetchDatabasePropertiesRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_environment(self, request: environments.GetEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetEnvironmentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_user_workloads_config_map(self, request: environments.GetUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_user_workloads_secret(self, request: environments.GetUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_environments(self, request: environments.ListEnvironmentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListEnvironmentsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_user_workloads_config_maps(self, request: environments.ListUserWorkloadsConfigMapsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListUserWorkloadsConfigMapsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_user_workloads_secrets(self, request: environments.ListUserWorkloadsSecretsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListUserWorkloadsSecretsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_workloads(self, request: environments.ListWorkloadsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListWorkloadsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_load_snapshot(self, request: environments.LoadSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.LoadSnapshotRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_poll_airflow_command(self, request: environments.PollAirflowCommandRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.PollAirflowCommandRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_save_snapshot(self, request: environments.SaveSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.SaveSnapshotRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_stop_airflow_command(self, request: environments.StopAirflowCommandRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.StopAirflowCommandRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_update_environment(self, request: environments.UpdateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateEnvironmentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_update_user_workloads_config_map(self, request: environments.UpdateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_update_user_workloads_secret(self, request: environments.UpdateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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(EnvironmentsTransport): - """REST 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 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 - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or 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 _CreateEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("CreateEnvironment") - - def __call__(self, - request: environments.CreateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/environments', - 'body': 'environment', - }, - ] - request, metadata = self._interceptor.pre_create_environment(request, metadata) - pb_request = environments.CreateEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_environment(resp) - return resp - - class _CreateUserWorkloadsConfigMap(EnvironmentsRestStub): - def __hash__(self): - return hash("CreateUserWorkloadsConfigMap") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.CreateUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', - 'body': 'user_workloads_config_map', - }, - ] - request, metadata = self._interceptor.pre_create_user_workloads_config_map(request, metadata) - pb_request = environments.CreateUserWorkloadsConfigMapRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _CreateUserWorkloadsSecret(EnvironmentsRestStub): - def __hash__(self): - return hash("CreateUserWorkloadsSecret") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.CreateUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', - 'body': 'user_workloads_secret', - }, - ] - request, metadata = self._interceptor.pre_create_user_workloads_secret(request, metadata) - pb_request = environments.CreateUserWorkloadsSecretRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _DatabaseFailover(EnvironmentsRestStub): - def __hash__(self): - return hash("DatabaseFailover") - - def __call__(self, - request: environments.DatabaseFailoverRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:databaseFailover', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_database_failover(request, metadata) - pb_request = environments.DatabaseFailoverRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_database_failover(resp) - return resp - - class _DeleteEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("DeleteEnvironment") - - def __call__(self, - request: environments.DeleteEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/environments/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_environment(request, metadata) - pb_request = environments.DeleteEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_environment(resp) - return resp - - class _DeleteUserWorkloadsConfigMap(EnvironmentsRestStub): - def __hash__(self): - return hash("DeleteUserWorkloadsConfigMap") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.DeleteUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_user_workloads_config_map(request, metadata) - pb_request = environments.DeleteUserWorkloadsConfigMapRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteUserWorkloadsSecret(EnvironmentsRestStub): - def __hash__(self): - return hash("DeleteUserWorkloadsSecret") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.DeleteUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_user_workloads_secret(request, metadata) - pb_request = environments.DeleteUserWorkloadsSecretRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _ExecuteAirflowCommand(EnvironmentsRestStub): - def __hash__(self): - return hash("ExecuteAirflowCommand") - - def __call__(self, - request: environments.ExecuteAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.ExecuteAirflowCommandResponse: - Response to - ExecuteAirflowCommandRequest. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:executeAirflowCommand', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_execute_airflow_command(request, metadata) - pb_request = environments.ExecuteAirflowCommandRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _FetchDatabaseProperties(EnvironmentsRestStub): - def __hash__(self): - return hash("FetchDatabaseProperties") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.FetchDatabasePropertiesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.FetchDatabasePropertiesResponse: - Response for - FetchDatabasePropertiesRequest. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:fetchDatabaseProperties', - }, - ] - request, metadata = self._interceptor.pre_fetch_database_properties(request, metadata) - pb_request = environments.FetchDatabasePropertiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _GetEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("GetEnvironment") - - def __call__(self, - request: environments.GetEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.Environment: - An environment for running - orchestration tasks. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/environments/*}', - }, - ] - request, metadata = self._interceptor.pre_get_environment(request, metadata) - pb_request = environments.GetEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _GetUserWorkloadsConfigMap(EnvironmentsRestStub): - def __hash__(self): - return hash("GetUserWorkloadsConfigMap") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.GetUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', - }, - ] - request, metadata = self._interceptor.pre_get_user_workloads_config_map(request, metadata) - pb_request = environments.GetUserWorkloadsConfigMapRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _GetUserWorkloadsSecret(EnvironmentsRestStub): - def __hash__(self): - return hash("GetUserWorkloadsSecret") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.GetUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', - }, - ] - request, metadata = self._interceptor.pre_get_user_workloads_secret(request, metadata) - pb_request = environments.GetUserWorkloadsSecretRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _ListEnvironments(EnvironmentsRestStub): - def __hash__(self): - return hash("ListEnvironments") - - def __call__(self, - request: environments.ListEnvironmentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.ListEnvironmentsResponse: - The environments in a project and - location. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/environments', - }, - ] - request, metadata = self._interceptor.pre_list_environments(request, metadata) - pb_request = environments.ListEnvironmentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _ListUserWorkloadsConfigMaps(EnvironmentsRestStub): - def __hash__(self): - return hash("ListUserWorkloadsConfigMaps") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.ListUserWorkloadsConfigMapsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.ListUserWorkloadsConfigMapsResponse: - The user workloads ConfigMaps for a - given environment. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', - }, - ] - request, metadata = self._interceptor.pre_list_user_workloads_config_maps(request, metadata) - pb_request = environments.ListUserWorkloadsConfigMapsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _ListUserWorkloadsSecrets(EnvironmentsRestStub): - def __hash__(self): - return hash("ListUserWorkloadsSecrets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.ListUserWorkloadsSecretsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.ListUserWorkloadsSecretsResponse: - The user workloads Secrets for a - given environment. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', - }, - ] - request, metadata = self._interceptor.pre_list_user_workloads_secrets(request, metadata) - pb_request = environments.ListUserWorkloadsSecretsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _ListWorkloads(EnvironmentsRestStub): - def __hash__(self): - return hash("ListWorkloads") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.ListWorkloadsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.ListWorkloadsResponse: - Response to ListWorkloadsRequest. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/environments/*}/workloads', - }, - ] - request, metadata = self._interceptor.pre_list_workloads(request, metadata) - pb_request = environments.ListWorkloadsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _LoadSnapshot(EnvironmentsRestStub): - def __hash__(self): - return hash("LoadSnapshot") - - def __call__(self, - request: environments.LoadSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:loadSnapshot', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_load_snapshot(request, metadata) - pb_request = environments.LoadSnapshotRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_load_snapshot(resp) - return resp - - class _PollAirflowCommand(EnvironmentsRestStub): - def __hash__(self): - return hash("PollAirflowCommand") - - def __call__(self, - request: environments.PollAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.PollAirflowCommandResponse: - Response to - PollAirflowCommandRequest. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:pollAirflowCommand', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_poll_airflow_command(request, metadata) - pb_request = environments.PollAirflowCommandRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _SaveSnapshot(EnvironmentsRestStub): - def __hash__(self): - return hash("SaveSnapshot") - - def __call__(self, - request: environments.SaveSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:saveSnapshot', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_save_snapshot(request, metadata) - pb_request = environments.SaveSnapshotRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_save_snapshot(resp) - return resp - - class _StopAirflowCommand(EnvironmentsRestStub): - def __hash__(self): - return hash("StopAirflowCommand") - - def __call__(self, - request: environments.StopAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.StopAirflowCommandResponse: - Response to - StopAirflowCommandRequest. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{environment=projects/*/locations/*/environments/*}:stopAirflowCommand', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_stop_airflow_command(request, metadata) - pb_request = environments.StopAirflowCommandRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _UpdateEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("UpdateEnvironment") - - def __call__(self, - request: environments.UpdateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{name=projects/*/locations/*/environments/*}', - 'body': 'environment', - }, - ] - request, metadata = self._interceptor.pre_update_environment(request, metadata) - pb_request = environments.UpdateEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_environment(resp) - return resp - - class _UpdateUserWorkloadsConfigMap(EnvironmentsRestStub): - def __hash__(self): - return hash("UpdateUserWorkloadsConfigMap") - - def __call__(self, - request: environments.UpdateUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', - 'body': 'user_workloads_config_map', - }, - ] - request, metadata = self._interceptor.pre_update_user_workloads_config_map(request, metadata) - pb_request = environments.UpdateUserWorkloadsConfigMapRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _UpdateUserWorkloadsSecret(EnvironmentsRestStub): - def __hash__(self): - return hash("UpdateUserWorkloadsSecret") - - def __call__(self, - request: environments.UpdateUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', - 'body': 'user_workloads_secret', - }, - ] - request, metadata = self._interceptor.pre_update_user_workloads_secret(request, metadata) - pb_request = environments.UpdateUserWorkloadsSecretRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - @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(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EnvironmentsRestTransport', -) 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 eb7f75b37afc..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,516 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 - - -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 = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) - - 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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 cbe5f4ed7477..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py +++ /dev/null @@ -1,863 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ImageVersionsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - ImageVersionsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 - - 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]] = ( - type(self).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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 135e62df605c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = image_versions.ListImageVersionsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1.types.ListImageVersionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = image_versions.ListImageVersionsRequest(request) - self._response = response - 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, 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/__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 2c4a6b349efb..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,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, - ), - } - - 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 8020a7751752..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,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.orchestration.airflow.service_v1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def 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 bb38a59a37cd..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,335 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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.grpc_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: gapic_v1.method_async.wrap_method( - self.list_image_versions, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__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 ebf61bdd9e19..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,533 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.cloud.orchestration.airflow.service_v1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore - -from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class 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, str]]) -> Tuple[image_versions.ListImageVersionsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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(ImageVersionsTransport): - """REST 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 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 - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - 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(ImageVersionsRestStub): - def __hash__(self): - return hash("ListImageVersions") - - def __call__(self, - request: image_versions.ListImageVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.image_versions.ListImageVersionsResponse: - The ImageVersions in a project and - location. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/imageVersions', - }, - ] - request, metadata = self._interceptor.pre_list_image_versions(request, metadata) - pb_request = image_versions.ListImageVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - 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(ImageVersionsRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ImageVersionsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ImageVersionsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ImageVersionsRestTransport', -) 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 f1c74173bd95..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.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 .environments import ( - 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__ = ( - '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 9d0a467d4cb0..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py +++ /dev/null @@ -1,2969 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', - 'CheckUpgradeResponse', - 'DataRetentionConfig', - 'TaskLogsRetentionConfig', - }, -) - - -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/ - """ - - 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/ - """ - - 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): - The configuration settings for software - inside the environment. - node_config (google.cloud.orchestration.airflow.service_v1.types.NodeConfig): - The configuration used for the Kubernetes - Engine cluster. - private_environment_config (google.cloud.orchestration.airflow.service_v1.types.PrivateEnvironmentConfig): - 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 will be applied. The default - value is Saturday and Sunday 00-06 GMT. - 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): - 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-*.*.\* 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-*.*.\* 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-*.*.\* 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-*.*.\* 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-*.*.\* 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. - - 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): - 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): - 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. - 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, - ) - storage_config: 'StorageConfig' = proto.Field( - proto.MESSAGE, - number=9, - message='StorageConfig', - ) - - -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: - task_logs_retention_config (google.cloud.orchestration.airflow.service_v1.types.TaskLogsRetentionConfig): - Optional. The configuration settings for task - logs retention - """ - - 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. For details, see - go/composer-store-task-logs-in-cloud-logging-only-design-doc - """ - 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, - ) - - -__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 5e3cfb5f1101..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" -] - -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.12" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/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"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/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('.') - # Remove once https://github.com/googleapis/python-api-core/pull/650 is merged - session.install("google-api-core>=2.19.1rc0") - 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_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 3fffc7af33c9..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,3851 +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.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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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 dcf2905a8c0c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py +++ /dev/null @@ -1,199 +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]] = { - '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 8f09d536771c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/setup.py +++ /dev/null @@ -1,93 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-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.7.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..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.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 diff --git a/owl-bot-staging/google-cloud-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 473c24f0bdfa..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py +++ /dev/null @@ -1,15930 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.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 - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateEnvironmentRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_create_environment_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateEnvironmentRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_environment in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_environment] = mock_object - - request = {} - await client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_environment(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=environments.CreateEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_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, - ) - 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 - - -def test_get_environment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetEnvironmentRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_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, - )) - response = await client.get_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetEnvironmentRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_environment in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_environment] = mock_object - - request = {} - await client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_environment_async(transport: str = 'grpc_asyncio', request_type=environments.GetEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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, - )) - 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 - - -@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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_environments() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListEnvironmentsRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListEnvironmentsRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_environments in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_environments] = mock_object - - request = {} - await client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_environments_async(transport: str = 'grpc_asyncio', request_type=environments.ListEnvironmentsRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_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 = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_environments(request={}) - - assert pager._metadata == expected_metadata - - 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=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__', 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=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__', 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateEnvironmentRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_update_environment_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateEnvironmentRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_environment in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_environment] = mock_object - - request = {} - await client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_environment(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteEnvironmentRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_delete_environment_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteEnvironmentRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_environment in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_environment] = mock_object - - request = {} - await client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_environment(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_environment_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ExecuteAirflowCommandRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ExecuteAirflowCommandRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.execute_airflow_command in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.execute_airflow_command] = mock_object - - request = {} - await client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_execute_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.ExecuteAirflowCommandRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.StopAirflowCommandRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.StopAirflowCommandRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.stop_airflow_command in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.stop_airflow_command] = mock_object - - request = {} - await client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.StopAirflowCommandRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.PollAirflowCommandRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.PollAirflowCommandRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.poll_airflow_command in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.poll_airflow_command] = mock_object - - request = {} - await client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_poll_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.PollAirflowCommandRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workloads() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListWorkloadsRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListWorkloadsRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_workloads in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_workloads] = mock_object - - request = {} - await client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_workloads_async(transport: str = 'grpc_asyncio', request_type=environments.ListWorkloadsRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_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 = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workloads(request={}) - - assert pager._metadata == expected_metadata - - 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=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__', 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=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__', 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsSecretRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsSecretRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_user_workloads_secret in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_user_workloads_secret] = mock_object - - request = {} - await client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsSecretRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsSecretRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_user_workloads_secret in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_user_workloads_secret] = mock_object - - request = {} - await client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsSecretsRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsSecretsRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_user_workloads_secrets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_user_workloads_secrets] = mock_object - - request = {} - await client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_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 = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_user_workloads_secrets(request={}) - - assert pager._metadata == expected_metadata - - 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=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__', 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=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__', 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsSecretRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsSecretRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_user_workloads_secret in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_user_workloads_secret] = mock_object - - request = {} - await client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsSecretRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsSecretRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_user_workloads_secret in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_user_workloads_secret] = mock_object - - request = {} - await client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsConfigMapRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsConfigMapRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_user_workloads_config_map in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_user_workloads_config_map] = mock_object - - request = {} - await client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsConfigMapRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsConfigMapRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_user_workloads_config_map in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_user_workloads_config_map] = mock_object - - request = {} - await client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsConfigMapsRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsConfigMapsRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_user_workloads_config_maps in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_user_workloads_config_maps] = mock_object - - request = {} - await client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_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 = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_user_workloads_config_maps(request={}) - - assert pager._metadata == expected_metadata - - 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=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__', 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=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__', 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_user_workloads_config_map in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_user_workloads_config_map] = mock_object - - request = {} - await client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_user_workloads_config_map in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_user_workloads_config_map] = mock_object - - request = {} - await client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.save_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.SaveSnapshotRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_save_snapshot_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.SaveSnapshotRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.save_snapshot in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.save_snapshot] = mock_object - - request = {} - await client.save_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.save_snapshot(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_save_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.SaveSnapshotRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.load_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.LoadSnapshotRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_load_snapshot_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.LoadSnapshotRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.load_snapshot in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.load_snapshot] = mock_object - - request = {} - await client.load_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.load_snapshot(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_load_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.LoadSnapshotRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.database_failover() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DatabaseFailoverRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_database_failover_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DatabaseFailoverRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.database_failover in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.database_failover] = mock_object - - request = {} - await client.database_failover(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.database_failover(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_database_failover_async(transport: str = 'grpc_asyncio', request_type=environments.DatabaseFailoverRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.FetchDatabasePropertiesRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.FetchDatabasePropertiesRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.fetch_database_properties in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.fetch_database_properties] = mock_object - - request = {} - await client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_fetch_database_properties_async(transport: str = 'grpc_asyncio', request_type=environments.FetchDatabasePropertiesRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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'] - - -@pytest.mark.parametrize("request_type", [ - environments.CreateEnvironmentRequest, - dict, -]) -def test_create_environment_rest(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': {'task_logs_retention_config': {'storage_mode': 1}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': 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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_environment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_create_environment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.CreateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_environment_rest_bad_request(transport: str = 'rest', request_type=environments.CreateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_environment(request) - - -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 - - 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_create_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetEnvironmentRequest, - dict, -]) -def test_get_environment_rest(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, - ) - - # 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 - 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 - -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 - - -@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, "pre_get_environment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.Environment.to_json(environments.Environment()) - - request = environments.GetEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.Environment() - - client.get_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_environment_rest_bad_request(transport: str = 'rest', request_type=environments.GetEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_environment(request) - - -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 - - 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_get_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListEnvironmentsRequest, - dict, -]) -def test_list_environments_rest(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 = 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 - 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' - -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 - - -@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, "pre_list_environments") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.ListEnvironmentsResponse.to_json(environments.ListEnvironmentsResponse()) - - request = environments.ListEnvironmentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListEnvironmentsResponse() - - client.list_environments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_environments_rest_bad_request(transport: str = 'rest', request_type=environments.ListEnvironmentsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_environments(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateEnvironmentRequest, - dict, -]) -def test_update_environment_rest(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': {'task_logs_retention_config': {'storage_mode': 1}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}, 'satisfies_pzs': 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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_environment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_update_environment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.UpdateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_environment_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_environment(request) - - -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 - - 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_update_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteEnvironmentRequest, - dict, -]) -def test_delete_environment_rest(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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_environment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_delete_environment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.DeleteEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_environment_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_environment(request) - - -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 - - 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_delete_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ExecuteAirflowCommandRequest, - dict, -]) -def test_execute_airflow_command_rest(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 = Response() - 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 - 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' - -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 - - -@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, "pre_execute_airflow_command") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.ExecuteAirflowCommandResponse.to_json(environments.ExecuteAirflowCommandResponse()) - - request = environments.ExecuteAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ExecuteAirflowCommandResponse() - - client.execute_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_execute_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.ExecuteAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.execute_airflow_command(request) - - -def test_execute_airflow_command_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.StopAirflowCommandRequest, - dict, -]) -def test_stop_airflow_command_rest(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 = Response() - 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 - 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'] - -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 - - -@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, "pre_stop_airflow_command") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.StopAirflowCommandResponse.to_json(environments.StopAirflowCommandResponse()) - - request = environments.StopAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.StopAirflowCommandResponse() - - client.stop_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_stop_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.StopAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.stop_airflow_command(request) - - -def test_stop_airflow_command_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.PollAirflowCommandRequest, - dict, -]) -def test_poll_airflow_command_rest(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 = Response() - 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 - 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 - -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 - - -@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, "pre_poll_airflow_command") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.PollAirflowCommandResponse.to_json(environments.PollAirflowCommandResponse()) - - request = environments.PollAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.PollAirflowCommandResponse() - - client.poll_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_poll_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.PollAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.poll_airflow_command(request) - - -def test_poll_airflow_command_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListWorkloadsRequest, - dict, -]) -def test_list_workloads_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_list_workloads") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.ListWorkloadsResponse.to_json(environments.ListWorkloadsResponse()) - - request = environments.ListWorkloadsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListWorkloadsResponse() - - client.list_workloads(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workloads_rest_bad_request(transport: str = 'rest', request_type=environments.ListWorkloadsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_workloads(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsSecretRequest, - dict, -]) -def test_create_user_workloads_secret_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_create_user_workloads_secret") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - - request = environments.CreateUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - - client.create_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.CreateUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_user_workloads_secret(request) - - -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 - - 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_create_user_workloads_secret_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsSecretRequest, - dict, -]) -def test_get_user_workloads_secret_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_get_user_workloads_secret") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - - request = environments.GetUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - - client.get_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.GetUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_user_workloads_secret(request) - - -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 - - 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_get_user_workloads_secret_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsSecretsRequest, - dict, -]) -def test_list_user_workloads_secrets_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_list_user_workloads_secrets") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.ListUserWorkloadsSecretsResponse.to_json(environments.ListUserWorkloadsSecretsResponse()) - - request = environments.ListUserWorkloadsSecretsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListUserWorkloadsSecretsResponse() - - client.list_user_workloads_secrets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_user_workloads_secrets_rest_bad_request(transport: str = 'rest', request_type=environments.ListUserWorkloadsSecretsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_user_workloads_secrets(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateUserWorkloadsSecretRequest, - dict, -]) -def test_update_user_workloads_secret_rest(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 = 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 - 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' - -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 - - -@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, "pre_update_user_workloads_secret") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - - request = environments.UpdateUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - - client.update_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_user_workloads_secret(request) - - -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 - - 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_update_user_workloads_secret_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsSecretRequest, - dict, -]) -def test_delete_user_workloads_secret_rest(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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_user_workloads_secret(request) - - # Establish that the response is the type that we expect. - assert response is None - -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 - - 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", ))) - - -@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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - 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_delete_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_user_workloads_secret(request) - - -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 - - 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_delete_user_workloads_secret_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsConfigMapRequest, - dict, -]) -def test_create_user_workloads_config_map_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_create_user_workloads_config_map") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - - request = environments.CreateUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - - client.create_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.CreateUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_user_workloads_config_map(request) - - -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 - - 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_create_user_workloads_config_map_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsConfigMapRequest, - dict, -]) -def test_get_user_workloads_config_map_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_get_user_workloads_config_map") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - - request = environments.GetUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - - client.get_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.GetUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_user_workloads_config_map(request) - - -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 - - 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_get_user_workloads_config_map_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsConfigMapsRequest, - dict, -]) -def test_list_user_workloads_config_maps_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_list_user_workloads_config_maps") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.ListUserWorkloadsConfigMapsResponse.to_json(environments.ListUserWorkloadsConfigMapsResponse()) - - request = environments.ListUserWorkloadsConfigMapsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListUserWorkloadsConfigMapsResponse() - - client.list_user_workloads_config_maps(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_user_workloads_config_maps_rest_bad_request(transport: str = 'rest', request_type=environments.ListUserWorkloadsConfigMapsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_user_workloads_config_maps(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateUserWorkloadsConfigMapRequest, - dict, -]) -def test_update_user_workloads_config_map_rest(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 = 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 - 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' - -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 - - -@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, "pre_update_user_workloads_config_map") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - - request = environments.UpdateUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - - client.update_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_user_workloads_config_map(request) - - -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 - - 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_update_user_workloads_config_map_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsConfigMapRequest, - dict, -]) -def test_delete_user_workloads_config_map_rest(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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_user_workloads_config_map(request) - - # Establish that the response is the type that we expect. - assert response is None - -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 - - 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", ))) - - -@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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - 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_delete_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_user_workloads_config_map(request) - - -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 - - 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_delete_user_workloads_config_map_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.SaveSnapshotRequest, - dict, -]) -def test_save_snapshot_rest(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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.save_snapshot(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_save_snapshot") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.SaveSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.save_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_save_snapshot_rest_bad_request(transport: str = 'rest', request_type=environments.SaveSnapshotRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.save_snapshot(request) - - -def test_save_snapshot_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.LoadSnapshotRequest, - dict, -]) -def test_load_snapshot_rest(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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.load_snapshot(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_load_snapshot") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.LoadSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.load_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_load_snapshot_rest_bad_request(transport: str = 'rest', request_type=environments.LoadSnapshotRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.load_snapshot(request) - - -def test_load_snapshot_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DatabaseFailoverRequest, - dict, -]) -def test_database_failover_rest(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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.database_failover(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_database_failover") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.DatabaseFailoverRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.database_failover(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_database_failover_rest_bad_request(transport: str = 'rest', request_type=environments.DatabaseFailoverRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.database_failover(request) - - -def test_database_failover_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.FetchDatabasePropertiesRequest, - dict, -]) -def test_fetch_database_properties_rest(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 = 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 - 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 - -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 - - 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", ))) - - -@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, "pre_fetch_database_properties") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.FetchDatabasePropertiesResponse.to_json(environments.FetchDatabasePropertiesResponse()) - - request = environments.FetchDatabasePropertiesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.FetchDatabasePropertiesResponse() - - client.fetch_database_properties(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_fetch_database_properties_rest_bad_request(transport: str = 'rest', request_type=environments.FetchDatabasePropertiesRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.fetch_database_properties(request) - - -def test_fetch_database_properties_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = EnvironmentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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', - '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) - - -def test_environments_rest_lro_client(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_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.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) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = 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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = 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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = 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 95050bfab6ec..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py +++ /dev/null @@ -1,2739 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import 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.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 - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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("client_class,transport_class,transport_name", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_image_versions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == image_versions.ListImageVersionsRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ImageVersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == image_versions.ListImageVersionsRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_image_versions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_image_versions] = mock_object - - request = {} - await client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_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 = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_image_versions(request={}) - - assert pager._metadata == expected_metadata - - 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=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__', 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=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__', 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 - - -@pytest.mark.parametrize("request_type", [ - image_versions.ListImageVersionsRequest, - dict, -]) -def test_list_image_versions_rest(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 = 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 - 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' - -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 - - -@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, "pre_list_image_versions") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = image_versions.ListImageVersionsResponse.to_json(image_versions.ListImageVersionsResponse()) - - request = image_versions.ListImageVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = image_versions.ListImageVersionsResponse() - - client.list_image_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_image_versions_rest_bad_request(transport: str = 'rest', request_type=image_versions.ListImageVersionsRequest): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_image_versions(request) - - -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 - - 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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ImageVersionsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ImageVersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = 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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = 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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = 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 5a08580483e9..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/README.rst +++ /dev/null @@ -1,49 +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 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 5c7ba31b939d..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 1fb16b4fa792..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py +++ /dev/null @@ -1,3261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 - - -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 = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) - - 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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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. - has_flattened_params = any([parent, environment]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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. - has_flattened_params = any([name, environment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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-3.\ *.*-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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, user_workloads_secret]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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, str]] = (), - ) -> 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-*.*.\* 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> pagers.ListUserWorkloadsSecretsAsyncPager: - r"""Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([user_workloads_secret]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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, str]] = (), - ) -> None: - r"""Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, user_workloads_config_map]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> pagers.ListUserWorkloadsConfigMapsAsyncPager: - r"""Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([user_workloads_config_map]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request 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, str]] = (), - ) -> None: - r"""Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 2618a30bd48d..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py +++ /dev/null @@ -1,3620 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = EnvironmentsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - EnvironmentsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 - - 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]] = ( - type(self).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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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. - has_flattened_params = any([parent, environment]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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. - has_flattened_params = any([name, environment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> 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-3.\ *.*-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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Creates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, user_workloads_secret]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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, str]] = (), - ) -> 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-*.*.\* 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> pagers.ListUserWorkloadsSecretsPager: - r"""Lists user workloads Secrets. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsSecret: - r"""Updates a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([user_workloads_secret]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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, str]] = (), - ) -> None: - r"""Deletes a user workloads Secret. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Creates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, user_workloads_config_map]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Gets an existing user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> pagers.ListUserWorkloadsConfigMapsPager: - r"""Lists user workloads ConfigMaps. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> environments.UserWorkloadsConfigMap: - r"""Updates a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([user_workloads_config_map]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request 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, str]] = (), - ) -> None: - r"""Deletes a user workloads ConfigMap. - - This method is supported for Cloud Composer environments in - versions composer-3.\ *.*-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_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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 45f5dd2349b1..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py +++ /dev/null @@ -1,502 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListEnvironmentsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListEnvironmentsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListWorkloadsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListWorkloadsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListWorkloadsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListUserWorkloadsSecretsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsSecretsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListUserWorkloadsSecretsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListUserWorkloadsConfigMapsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListUserWorkloadsConfigMapsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = environments.ListUserWorkloadsConfigMapsRequest(request) - self._response = response - 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, 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/__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 6059007c51a1..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py +++ /dev/null @@ -1,525 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, - ), - } - - 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 f6eeb73c349c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py +++ /dev/null @@ -1,1019 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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-3.\ *.*-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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def 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 5956a37637fc..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,1149 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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-3.\ *.*-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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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-*.*.\* 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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: gapic_v1.method_async.wrap_method( - self.create_environment, - default_timeout=None, - client_info=client_info, - ), - self.get_environment: gapic_v1.method_async.wrap_method( - self.get_environment, - default_timeout=None, - client_info=client_info, - ), - self.list_environments: gapic_v1.method_async.wrap_method( - self.list_environments, - default_timeout=None, - client_info=client_info, - ), - self.update_environment: gapic_v1.method_async.wrap_method( - self.update_environment, - default_timeout=None, - client_info=client_info, - ), - self.delete_environment: gapic_v1.method_async.wrap_method( - self.delete_environment, - default_timeout=None, - client_info=client_info, - ), - self.restart_web_server: gapic_v1.method_async.wrap_method( - self.restart_web_server, - default_timeout=None, - client_info=client_info, - ), - self.check_upgrade: gapic_v1.method_async.wrap_method( - self.check_upgrade, - default_timeout=None, - client_info=client_info, - ), - self.execute_airflow_command: gapic_v1.method_async.wrap_method( - self.execute_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.stop_airflow_command: gapic_v1.method_async.wrap_method( - self.stop_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.poll_airflow_command: gapic_v1.method_async.wrap_method( - self.poll_airflow_command, - default_timeout=None, - client_info=client_info, - ), - self.list_workloads: gapic_v1.method_async.wrap_method( - self.list_workloads, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_secret: gapic_v1.method_async.wrap_method( - self.create_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_secret: gapic_v1.method_async.wrap_method( - self.get_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_secrets: gapic_v1.method_async.wrap_method( - self.list_user_workloads_secrets, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_secret: gapic_v1.method_async.wrap_method( - self.update_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_secret: gapic_v1.method_async.wrap_method( - self.delete_user_workloads_secret, - default_timeout=None, - client_info=client_info, - ), - self.create_user_workloads_config_map: gapic_v1.method_async.wrap_method( - self.create_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.get_user_workloads_config_map: gapic_v1.method_async.wrap_method( - self.get_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.list_user_workloads_config_maps: gapic_v1.method_async.wrap_method( - self.list_user_workloads_config_maps, - default_timeout=None, - client_info=client_info, - ), - self.update_user_workloads_config_map: gapic_v1.method_async.wrap_method( - self.update_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.delete_user_workloads_config_map: gapic_v1.method_async.wrap_method( - self.delete_user_workloads_config_map, - default_timeout=None, - client_info=client_info, - ), - self.save_snapshot: gapic_v1.method_async.wrap_method( - self.save_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.load_snapshot: gapic_v1.method_async.wrap_method( - self.load_snapshot, - default_timeout=None, - client_info=client_info, - ), - self.database_failover: gapic_v1.method_async.wrap_method( - self.database_failover, - default_timeout=None, - client_info=client_info, - ), - self.fetch_database_properties: gapic_v1.method_async.wrap_method( - self.fetch_database_properties, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__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 6ebbe966b003..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py +++ /dev/null @@ -1,3215 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -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 .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class 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, str]]) -> Tuple[environments.CheckUpgradeRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_create_environment(self, request: environments.CreateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateEnvironmentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_create_user_workloads_config_map(self, request: environments.CreateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_create_user_workloads_secret(self, request: environments.CreateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.CreateUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_database_failover(self, request: environments.DatabaseFailoverRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DatabaseFailoverRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_delete_environment(self, request: environments.DeleteEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DeleteEnvironmentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_delete_user_workloads_config_map(self, request: environments.DeleteUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.DeleteUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[environments.DeleteUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[environments.ExecuteAirflowCommandRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_fetch_database_properties(self, request: environments.FetchDatabasePropertiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.FetchDatabasePropertiesRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_environment(self, request: environments.GetEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetEnvironmentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_user_workloads_config_map(self, request: environments.GetUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_user_workloads_secret(self, request: environments.GetUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.GetUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_environments(self, request: environments.ListEnvironmentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListEnvironmentsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_user_workloads_config_maps(self, request: environments.ListUserWorkloadsConfigMapsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListUserWorkloadsConfigMapsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_user_workloads_secrets(self, request: environments.ListUserWorkloadsSecretsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListUserWorkloadsSecretsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_workloads(self, request: environments.ListWorkloadsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.ListWorkloadsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_load_snapshot(self, request: environments.LoadSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.LoadSnapshotRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_poll_airflow_command(self, request: environments.PollAirflowCommandRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.PollAirflowCommandRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_restart_web_server(self, request: environments.RestartWebServerRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.RestartWebServerRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_save_snapshot(self, request: environments.SaveSnapshotRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.SaveSnapshotRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_stop_airflow_command(self, request: environments.StopAirflowCommandRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.StopAirflowCommandRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_update_environment(self, request: environments.UpdateEnvironmentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateEnvironmentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_update_user_workloads_config_map(self, request: environments.UpdateUserWorkloadsConfigMapRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateUserWorkloadsConfigMapRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_update_user_workloads_secret(self, request: environments.UpdateUserWorkloadsSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[environments.UpdateUserWorkloadsSecretRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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(EnvironmentsTransport): - """REST 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 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 - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or 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(EnvironmentsRestStub): - def __hash__(self): - return hash("CheckUpgrade") - - def __call__(self, - request: environments.CheckUpgradeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:checkUpgrade', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_check_upgrade(request, metadata) - pb_request = environments.CheckUpgradeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_check_upgrade(resp) - return resp - - class _CreateEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("CreateEnvironment") - - def __call__(self, - request: environments.CreateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=projects/*/locations/*}/environments', - 'body': 'environment', - }, - ] - request, metadata = self._interceptor.pre_create_environment(request, metadata) - pb_request = environments.CreateEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_environment(resp) - return resp - - class _CreateUserWorkloadsConfigMap(EnvironmentsRestStub): - def __hash__(self): - return hash("CreateUserWorkloadsConfigMap") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.CreateUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', - 'body': 'user_workloads_config_map', - }, - ] - request, metadata = self._interceptor.pre_create_user_workloads_config_map(request, metadata) - pb_request = environments.CreateUserWorkloadsConfigMapRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _CreateUserWorkloadsSecret(EnvironmentsRestStub): - def __hash__(self): - return hash("CreateUserWorkloadsSecret") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.CreateUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', - 'body': 'user_workloads_secret', - }, - ] - request, metadata = self._interceptor.pre_create_user_workloads_secret(request, metadata) - pb_request = environments.CreateUserWorkloadsSecretRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _DatabaseFailover(EnvironmentsRestStub): - def __hash__(self): - return hash("DatabaseFailover") - - def __call__(self, - request: environments.DatabaseFailoverRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:databaseFailover', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_database_failover(request, metadata) - pb_request = environments.DatabaseFailoverRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_database_failover(resp) - return resp - - class _DeleteEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("DeleteEnvironment") - - def __call__(self, - request: environments.DeleteEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_environment(request, metadata) - pb_request = environments.DeleteEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_environment(resp) - return resp - - class _DeleteUserWorkloadsConfigMap(EnvironmentsRestStub): - def __hash__(self): - return hash("DeleteUserWorkloadsConfigMap") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.DeleteUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_user_workloads_config_map(request, metadata) - pb_request = environments.DeleteUserWorkloadsConfigMapRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteUserWorkloadsSecret(EnvironmentsRestStub): - def __hash__(self): - return hash("DeleteUserWorkloadsSecret") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.DeleteUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_user_workloads_secret(request, metadata) - pb_request = environments.DeleteUserWorkloadsSecretRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _ExecuteAirflowCommand(EnvironmentsRestStub): - def __hash__(self): - return hash("ExecuteAirflowCommand") - - def __call__(self, - request: environments.ExecuteAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.ExecuteAirflowCommandResponse: - Response to - ExecuteAirflowCommandRequest. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:executeAirflowCommand', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_execute_airflow_command(request, metadata) - pb_request = environments.ExecuteAirflowCommandRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _FetchDatabaseProperties(EnvironmentsRestStub): - def __hash__(self): - return hash("FetchDatabaseProperties") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.FetchDatabasePropertiesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.FetchDatabasePropertiesResponse: - Response for - FetchDatabasePropertiesRequest. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:fetchDatabaseProperties', - }, - ] - request, metadata = self._interceptor.pre_fetch_database_properties(request, metadata) - pb_request = environments.FetchDatabasePropertiesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _GetEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("GetEnvironment") - - def __call__(self, - request: environments.GetEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.Environment: - An environment for running - orchestration tasks. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*}', - }, - ] - request, metadata = self._interceptor.pre_get_environment(request, metadata) - pb_request = environments.GetEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _GetUserWorkloadsConfigMap(EnvironmentsRestStub): - def __hash__(self): - return hash("GetUserWorkloadsConfigMap") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.GetUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', - }, - ] - request, metadata = self._interceptor.pre_get_user_workloads_config_map(request, metadata) - pb_request = environments.GetUserWorkloadsConfigMapRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _GetUserWorkloadsSecret(EnvironmentsRestStub): - def __hash__(self): - return hash("GetUserWorkloadsSecret") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.GetUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', - }, - ] - request, metadata = self._interceptor.pre_get_user_workloads_secret(request, metadata) - pb_request = environments.GetUserWorkloadsSecretRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _ListEnvironments(EnvironmentsRestStub): - def __hash__(self): - return hash("ListEnvironments") - - def __call__(self, - request: environments.ListEnvironmentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.ListEnvironmentsResponse: - The environments in a project and - location. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=projects/*/locations/*}/environments', - }, - ] - request, metadata = self._interceptor.pre_list_environments(request, metadata) - pb_request = environments.ListEnvironmentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _ListUserWorkloadsConfigMaps(EnvironmentsRestStub): - def __hash__(self): - return hash("ListUserWorkloadsConfigMaps") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.ListUserWorkloadsConfigMapsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.ListUserWorkloadsConfigMapsResponse: - The user workloads ConfigMaps for a - given environment. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsConfigMaps', - }, - ] - request, metadata = self._interceptor.pre_list_user_workloads_config_maps(request, metadata) - pb_request = environments.ListUserWorkloadsConfigMapsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _ListUserWorkloadsSecrets(EnvironmentsRestStub): - def __hash__(self): - return hash("ListUserWorkloadsSecrets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.ListUserWorkloadsSecretsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.ListUserWorkloadsSecretsResponse: - The user workloads Secrets for a - given environment. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=projects/*/locations/*/environments/*}/userWorkloadsSecrets', - }, - ] - request, metadata = self._interceptor.pre_list_user_workloads_secrets(request, metadata) - pb_request = environments.ListUserWorkloadsSecretsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _ListWorkloads(EnvironmentsRestStub): - def __hash__(self): - return hash("ListWorkloads") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.ListWorkloadsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.ListWorkloadsResponse: - Response to ListWorkloadsRequest. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=projects/*/locations/*/environments/*}/workloads', - }, - ] - request, metadata = self._interceptor.pre_list_workloads(request, metadata) - pb_request = environments.ListWorkloadsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _LoadSnapshot(EnvironmentsRestStub): - def __hash__(self): - return hash("LoadSnapshot") - - def __call__(self, - request: environments.LoadSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:loadSnapshot', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_load_snapshot(request, metadata) - pb_request = environments.LoadSnapshotRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_load_snapshot(resp) - return resp - - class _PollAirflowCommand(EnvironmentsRestStub): - def __hash__(self): - return hash("PollAirflowCommand") - - def __call__(self, - request: environments.PollAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.PollAirflowCommandResponse: - Response to - PollAirflowCommandRequest. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:pollAirflowCommand', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_poll_airflow_command(request, metadata) - pb_request = environments.PollAirflowCommandRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _RestartWebServer(EnvironmentsRestStub): - def __hash__(self): - return hash("RestartWebServer") - - def __call__(self, - request: environments.RestartWebServerRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*}:restartWebServer', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_restart_web_server(request, metadata) - pb_request = environments.RestartWebServerRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_restart_web_server(resp) - return resp - - class _SaveSnapshot(EnvironmentsRestStub): - def __hash__(self): - return hash("SaveSnapshot") - - def __call__(self, - request: environments.SaveSnapshotRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:saveSnapshot', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_save_snapshot(request, metadata) - pb_request = environments.SaveSnapshotRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_save_snapshot(resp) - return resp - - class _StopAirflowCommand(EnvironmentsRestStub): - def __hash__(self): - return hash("StopAirflowCommand") - - def __call__(self, - request: environments.StopAirflowCommandRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.StopAirflowCommandResponse: - Response to - StopAirflowCommandRequest. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta1/{environment=projects/*/locations/*/environments/*}:stopAirflowCommand', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_stop_airflow_command(request, metadata) - pb_request = environments.StopAirflowCommandRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _UpdateEnvironment(EnvironmentsRestStub): - def __hash__(self): - return hash("UpdateEnvironment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: environments.UpdateEnvironmentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta1/{name=projects/*/locations/*/environments/*}', - 'body': 'environment', - }, - ] - request, metadata = self._interceptor.pre_update_environment(request, metadata) - pb_request = environments.UpdateEnvironmentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_environment(resp) - return resp - - class _UpdateUserWorkloadsConfigMap(EnvironmentsRestStub): - def __hash__(self): - return hash("UpdateUserWorkloadsConfigMap") - - def __call__(self, - request: environments.UpdateUserWorkloadsConfigMapRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsConfigMap: - User workloads ConfigMap used by - Airflow tasks that run with Kubernetes - executor or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1beta1/{user_workloads_config_map.name=projects/*/locations/*/environments/*/userWorkloadsConfigMaps/*}', - 'body': 'user_workloads_config_map', - }, - ] - request, metadata = self._interceptor.pre_update_user_workloads_config_map(request, metadata) - pb_request = environments.UpdateUserWorkloadsConfigMapRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - return resp - - class _UpdateUserWorkloadsSecret(EnvironmentsRestStub): - def __hash__(self): - return hash("UpdateUserWorkloadsSecret") - - def __call__(self, - request: environments.UpdateUserWorkloadsSecretRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.environments.UserWorkloadsSecret: - User workloads Secret used by Airflow - tasks that run with Kubernetes executor - or KubernetesPodOperator. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1beta1/{user_workloads_secret.name=projects/*/locations/*/environments/*/userWorkloadsSecrets/*}', - 'body': 'user_workloads_secret', - }, - ] - request, metadata = self._interceptor.pre_update_user_workloads_secret(request, metadata) - pb_request = environments.UpdateUserWorkloadsSecretRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - 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(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(EnvironmentsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EnvironmentsRestTransport', -) 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 bedf994089db..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,516 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 - - -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 = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) - - 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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 ed14e2e66caa..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py +++ /dev/null @@ -1,863 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.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 - -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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = ImageVersionsClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - ImageVersionsClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 - - 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]] = ( - type(self).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, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, 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, - 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, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # 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 edf23d8c6f79..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = image_versions.ListImageVersionsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsRequest): - The initial request object. - response (google.cloud.orchestration.airflow.service_v1beta1.types.ListImageVersionsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = image_versions.ListImageVersionsRequest(request) - self._response = response - 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, 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/__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 32089ad848d8..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,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, - ), - } - - 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 fb20b510e423..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,325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore -from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def 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 8d8dda7560a5..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,335 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.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 - - -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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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.grpc_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: gapic_v1.method_async.wrap_method( - self.list_image_versions, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__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 eb609417c796..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,533 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions -from google.longrunning import operations_pb2 # type: ignore - -from .base import ImageVersionsTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class 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, str]]) -> Tuple[image_versions.ListImageVersionsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the 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(ImageVersionsTransport): - """REST 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 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 - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - 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(ImageVersionsRestStub): - def __hash__(self): - return hash("ListImageVersions") - - def __call__(self, - request: image_versions.ListImageVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.image_versions.ListImageVersionsResponse: - The ImageVersions in a project and - location. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{parent=projects/*/locations/*}/imageVersions', - }, - ] - request, metadata = self._interceptor.pre_list_image_versions(request, metadata) - pb_request = image_versions.ListImageVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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) - 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(ImageVersionsRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ImageVersionsRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ImageVersionsRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ImageVersionsRestTransport', -) 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 54f4f24cc1a2..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py +++ /dev/null @@ -1,3146 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/ - """ - - 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/ - """ - - 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): - The configuration settings for software - inside the environment. - node_config (google.cloud.orchestration.airflow.service_v1beta1.types.NodeConfig): - The configuration used for the Kubernetes - Engine cluster. - private_environment_config (google.cloud.orchestration.airflow.service_v1beta1.types.PrivateEnvironmentConfig): - 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): - 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-*.*.\* 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-*.*.\* 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-*.*.\* 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-*.*.\* 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-*.*.\* 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-*.*.\* 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): - 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): - 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. - 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, - ) - 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 020f6ffc86cb..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" -] - -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.12" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/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"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/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('.') - # Remove once https://github.com/googleapis/python-api-core/pull/650 is merged - session.install("google-api-core>=2.19.1rc0") - 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 4c413d500bdb..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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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 d6d51f4e7b2b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/setup.py +++ /dev/null @@ -1,93 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-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.7.txt b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..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.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 diff --git a/owl-bot-staging/google-cloud-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 6efeb82b0506..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py +++ /dev/null @@ -1,16831 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.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 - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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("client_class,transport_class,transport_name", [ - (EnvironmentsClient, transports.EnvironmentsGrpcTransport, "grpc"), - (EnvironmentsClient, transports.EnvironmentsRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateEnvironmentRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_create_environment_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateEnvironmentRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_environment in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_environment] = mock_object - - request = {} - await client.create_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_environment(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_create_environment_async(transport: str = 'grpc_asyncio', request_type=environments.CreateEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_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, - ) - 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 - - -def test_get_environment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetEnvironmentRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_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, - )) - response = await client.get_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetEnvironmentRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_environment in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_environment] = mock_object - - request = {} - await client.get_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_get_environment_async(transport: str = 'grpc_asyncio', request_type=environments.GetEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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, - )) - 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 - - -@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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_environments), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_environments() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListEnvironmentsRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListEnvironmentsRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_environments in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_environments] = mock_object - - request = {} - await client.list_environments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_environments_async(transport: str = 'grpc_asyncio', request_type=environments.ListEnvironmentsRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_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 = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_environments(request={}) - - assert pager._metadata == expected_metadata - - 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=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__', 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=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__', 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateEnvironmentRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_update_environment_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateEnvironmentRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_environment in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_environment] = mock_object - - request = {} - await client.update_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_environment(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_update_environment_async(transport: str = 'grpc_asyncio', request_type=environments.UpdateEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_environment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_environment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteEnvironmentRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_delete_environment_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteEnvironmentRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_environment in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_environment] = mock_object - - request = {} - await client.delete_environment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_environment(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_environment_async(transport: str = 'grpc_asyncio', request_type=environments.DeleteEnvironmentRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.RestartWebServerRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_restart_web_server_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.RestartWebServerRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.restart_web_server in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.restart_web_server] = mock_object - - request = {} - await client.restart_web_server(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.restart_web_server(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_restart_web_server_async(transport: str = 'grpc_asyncio', request_type=environments.RestartWebServerRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.check_upgrade), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.check_upgrade() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CheckUpgradeRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_check_upgrade_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CheckUpgradeRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.check_upgrade in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.check_upgrade] = mock_object - - request = {} - await client.check_upgrade(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.check_upgrade(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_check_upgrade_async(transport: str = 'grpc_asyncio', request_type=environments.CheckUpgradeRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ExecuteAirflowCommandRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ExecuteAirflowCommandRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.execute_airflow_command in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.execute_airflow_command] = mock_object - - request = {} - await client.execute_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_execute_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.ExecuteAirflowCommandRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.StopAirflowCommandRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.StopAirflowCommandRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.stop_airflow_command in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.stop_airflow_command] = mock_object - - request = {} - await client.stop_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_stop_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.StopAirflowCommandRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.PollAirflowCommandRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.PollAirflowCommandRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.poll_airflow_command in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.poll_airflow_command] = mock_object - - request = {} - await client.poll_airflow_command(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_poll_airflow_command_async(transport: str = 'grpc_asyncio', request_type=environments.PollAirflowCommandRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_workloads), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_workloads() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListWorkloadsRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListWorkloadsRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_workloads in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_workloads] = mock_object - - request = {} - await client.list_workloads(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_list_workloads_async(transport: str = 'grpc_asyncio', request_type=environments.ListWorkloadsRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_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 = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_workloads(request={}) - - assert pager._metadata == expected_metadata - - 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=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__', 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=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__', 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsSecretRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsSecretRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_user_workloads_secret in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_user_workloads_secret] = mock_object - - request = {} - await client.create_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsSecretRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsSecretRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_user_workloads_secret in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_user_workloads_secret] = mock_object - - request = {} - await client.get_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsSecretsRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsSecretsRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_user_workloads_secrets in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_user_workloads_secrets] = mock_object - - request = {} - await client.list_user_workloads_secrets(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_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 = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_user_workloads_secrets(request={}) - - assert pager._metadata == expected_metadata - - 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=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__', 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=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__', 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsSecretRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsSecretRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_user_workloads_secret in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_user_workloads_secret] = mock_object - - request = {} - await client.update_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsSecretRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsSecretRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_user_workloads_secret in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_user_workloads_secret] = mock_object - - request = {} - await client.delete_user_workloads_secret(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsConfigMapRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.CreateUserWorkloadsConfigMapRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_user_workloads_config_map in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.create_user_workloads_config_map] = mock_object - - request = {} - await client.create_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsConfigMapRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.GetUserWorkloadsConfigMapRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_user_workloads_config_map in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.get_user_workloads_config_map] = mock_object - - request = {} - await client.get_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsConfigMapsRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.ListUserWorkloadsConfigMapsRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_user_workloads_config_maps in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_user_workloads_config_maps] = mock_object - - request = {} - await client.list_user_workloads_config_maps(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_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 = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_user_workloads_config_maps(request={}) - - assert pager._metadata == expected_metadata - - 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=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__', 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=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__', 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.UpdateUserWorkloadsConfigMapRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_user_workloads_config_map in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.update_user_workloads_config_map] = mock_object - - request = {} - await client.update_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DeleteUserWorkloadsConfigMapRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_user_workloads_config_map in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.delete_user_workloads_config_map] = mock_object - - request = {} - await client.delete_user_workloads_config_map(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.save_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.save_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.SaveSnapshotRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_save_snapshot_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.SaveSnapshotRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.save_snapshot in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.save_snapshot] = mock_object - - request = {} - await client.save_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.save_snapshot(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_save_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.SaveSnapshotRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.load_snapshot), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.load_snapshot() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.LoadSnapshotRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_load_snapshot_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.LoadSnapshotRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.load_snapshot in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.load_snapshot] = mock_object - - request = {} - await client.load_snapshot(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.load_snapshot(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_load_snapshot_async(transport: str = 'grpc_asyncio', request_type=environments.LoadSnapshotRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.database_failover), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.database_failover() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DatabaseFailoverRequest() - - -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 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 - -@pytest.mark.asyncio -async def test_database_failover_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.DatabaseFailoverRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.database_failover in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.database_failover] = mock_object - - request = {} - await client.database_failover(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.database_failover(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - -@pytest.mark.asyncio -async def test_database_failover_async(transport: str = 'grpc_asyncio', request_type=environments.DatabaseFailoverRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.FetchDatabasePropertiesRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == environments.FetchDatabasePropertiesRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.fetch_database_properties in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.fetch_database_properties] = mock_object - - request = {} - await client.fetch_database_properties(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.call_count == 2 - -@pytest.mark.asyncio -async def test_fetch_database_properties_async(transport: str = 'grpc_asyncio', request_type=environments.FetchDatabasePropertiesRequest): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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'] - - -@pytest.mark.parametrize("request_type", [ - environments.CreateEnvironmentRequest, - dict, -]) -def test_create_environment_rest(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, '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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_environment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_create_environment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.CreateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_environment_rest_bad_request(transport: str = 'rest', request_type=environments.CreateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_environment(request) - - -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 - - 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_create_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetEnvironmentRequest, - dict, -]) -def test_get_environment_rest(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, - ) - - # 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 - 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 - -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 - - -@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, "pre_get_environment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.Environment.to_json(environments.Environment()) - - request = environments.GetEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.Environment() - - client.get_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_environment_rest_bad_request(transport: str = 'rest', request_type=environments.GetEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_environment(request) - - -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 - - 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_get_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListEnvironmentsRequest, - dict, -]) -def test_list_environments_rest(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 = 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 - 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' - -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 - - -@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, "pre_list_environments") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.ListEnvironmentsResponse.to_json(environments.ListEnvironmentsResponse()) - - request = environments.ListEnvironmentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListEnvironmentsResponse() - - client.list_environments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_environments_rest_bad_request(transport: str = 'rest', request_type=environments.ListEnvironmentsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_environments(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateEnvironmentRequest, - dict, -]) -def test_update_environment_rest(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, '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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_environment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - 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", ))) - - -@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, "pre_update_environment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.UpdateEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_environment_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_environment(request) - - -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 - - 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_update_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteEnvironmentRequest, - dict, -]) -def test_delete_environment_rest(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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_environment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_delete_environment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.DeleteEnvironmentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_environment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_environment_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteEnvironmentRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_environment(request) - - -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 - - 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_delete_environment_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.RestartWebServerRequest, - dict, -]) -def test_restart_web_server_rest(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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.restart_web_server(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_restart_web_server") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.RestartWebServerRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.restart_web_server(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_restart_web_server_rest_bad_request(transport: str = 'rest', request_type=environments.RestartWebServerRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.restart_web_server(request) - - -def test_restart_web_server_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.CheckUpgradeRequest, - dict, -]) -def test_check_upgrade_rest(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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.check_upgrade(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_check_upgrade") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.CheckUpgradeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.check_upgrade(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_check_upgrade_rest_bad_request(transport: str = 'rest', request_type=environments.CheckUpgradeRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.check_upgrade(request) - - -def test_check_upgrade_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ExecuteAirflowCommandRequest, - dict, -]) -def test_execute_airflow_command_rest(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 = Response() - 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 - 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' - -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 - - -@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, "pre_execute_airflow_command") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.ExecuteAirflowCommandResponse.to_json(environments.ExecuteAirflowCommandResponse()) - - request = environments.ExecuteAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ExecuteAirflowCommandResponse() - - client.execute_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_execute_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.ExecuteAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.execute_airflow_command(request) - - -def test_execute_airflow_command_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.StopAirflowCommandRequest, - dict, -]) -def test_stop_airflow_command_rest(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 = Response() - 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 - 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'] - -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 - - -@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, "pre_stop_airflow_command") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.StopAirflowCommandResponse.to_json(environments.StopAirflowCommandResponse()) - - request = environments.StopAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.StopAirflowCommandResponse() - - client.stop_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_stop_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.StopAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.stop_airflow_command(request) - - -def test_stop_airflow_command_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.PollAirflowCommandRequest, - dict, -]) -def test_poll_airflow_command_rest(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 = Response() - 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 - 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 - -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 - - -@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, "pre_poll_airflow_command") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.PollAirflowCommandResponse.to_json(environments.PollAirflowCommandResponse()) - - request = environments.PollAirflowCommandRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.PollAirflowCommandResponse() - - client.poll_airflow_command(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_poll_airflow_command_rest_bad_request(transport: str = 'rest', request_type=environments.PollAirflowCommandRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.poll_airflow_command(request) - - -def test_poll_airflow_command_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListWorkloadsRequest, - dict, -]) -def test_list_workloads_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_list_workloads") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.ListWorkloadsResponse.to_json(environments.ListWorkloadsResponse()) - - request = environments.ListWorkloadsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListWorkloadsResponse() - - client.list_workloads(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_workloads_rest_bad_request(transport: str = 'rest', request_type=environments.ListWorkloadsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_workloads(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsSecretRequest, - dict, -]) -def test_create_user_workloads_secret_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_create_user_workloads_secret") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - - request = environments.CreateUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - - client.create_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.CreateUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_user_workloads_secret(request) - - -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 - - 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_create_user_workloads_secret_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsSecretRequest, - dict, -]) -def test_get_user_workloads_secret_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_get_user_workloads_secret") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - - request = environments.GetUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - - client.get_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.GetUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_user_workloads_secret(request) - - -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 - - 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_get_user_workloads_secret_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsSecretsRequest, - dict, -]) -def test_list_user_workloads_secrets_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_list_user_workloads_secrets") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.ListUserWorkloadsSecretsResponse.to_json(environments.ListUserWorkloadsSecretsResponse()) - - request = environments.ListUserWorkloadsSecretsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListUserWorkloadsSecretsResponse() - - client.list_user_workloads_secrets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_user_workloads_secrets_rest_bad_request(transport: str = 'rest', request_type=environments.ListUserWorkloadsSecretsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_user_workloads_secrets(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateUserWorkloadsSecretRequest, - dict, -]) -def test_update_user_workloads_secret_rest(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 = 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 - 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' - -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 - - -@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, "pre_update_user_workloads_secret") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsSecret.to_json(environments.UserWorkloadsSecret()) - - request = environments.UpdateUserWorkloadsSecretRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsSecret() - - client.update_user_workloads_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_user_workloads_secret(request) - - -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 - - 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_update_user_workloads_secret_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsSecretRequest, - dict, -]) -def test_delete_user_workloads_secret_rest(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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_user_workloads_secret(request) - - # Establish that the response is the type that we expect. - assert response is None - -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 - - 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", ))) - - -@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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - 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_delete_user_workloads_secret_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteUserWorkloadsSecretRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_user_workloads_secret(request) - - -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 - - 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_delete_user_workloads_secret_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.CreateUserWorkloadsConfigMapRequest, - dict, -]) -def test_create_user_workloads_config_map_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_create_user_workloads_config_map") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - - request = environments.CreateUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - - client.create_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.CreateUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_user_workloads_config_map(request) - - -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 - - 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_create_user_workloads_config_map_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.GetUserWorkloadsConfigMapRequest, - dict, -]) -def test_get_user_workloads_config_map_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_get_user_workloads_config_map") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - - request = environments.GetUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - - client.get_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.GetUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_user_workloads_config_map(request) - - -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 - - 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_get_user_workloads_config_map_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.ListUserWorkloadsConfigMapsRequest, - dict, -]) -def test_list_user_workloads_config_maps_rest(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 = 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 - 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' - -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 - - 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", ))) - - -@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, "pre_list_user_workloads_config_maps") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.ListUserWorkloadsConfigMapsResponse.to_json(environments.ListUserWorkloadsConfigMapsResponse()) - - request = environments.ListUserWorkloadsConfigMapsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.ListUserWorkloadsConfigMapsResponse() - - client.list_user_workloads_config_maps(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_user_workloads_config_maps_rest_bad_request(transport: str = 'rest', request_type=environments.ListUserWorkloadsConfigMapsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_user_workloads_config_maps(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - environments.UpdateUserWorkloadsConfigMapRequest, - dict, -]) -def test_update_user_workloads_config_map_rest(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 = 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 - 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' - -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 - - -@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, "pre_update_user_workloads_config_map") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.UserWorkloadsConfigMap.to_json(environments.UserWorkloadsConfigMap()) - - request = environments.UpdateUserWorkloadsConfigMapRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.UserWorkloadsConfigMap() - - client.update_user_workloads_config_map(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.UpdateUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_user_workloads_config_map(request) - - -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 - - 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_update_user_workloads_config_map_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DeleteUserWorkloadsConfigMapRequest, - dict, -]) -def test_delete_user_workloads_config_map_rest(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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_user_workloads_config_map(request) - - # Establish that the response is the type that we expect. - assert response is None - -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 - - 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", ))) - - -@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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - 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_delete_user_workloads_config_map_rest_bad_request(transport: str = 'rest', request_type=environments.DeleteUserWorkloadsConfigMapRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_user_workloads_config_map(request) - - -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 - - 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_delete_user_workloads_config_map_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.SaveSnapshotRequest, - dict, -]) -def test_save_snapshot_rest(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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.save_snapshot(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_save_snapshot") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.SaveSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.save_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_save_snapshot_rest_bad_request(transport: str = 'rest', request_type=environments.SaveSnapshotRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.save_snapshot(request) - - -def test_save_snapshot_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.LoadSnapshotRequest, - dict, -]) -def test_load_snapshot_rest(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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.load_snapshot(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_load_snapshot") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.LoadSnapshotRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.load_snapshot(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_load_snapshot_rest_bad_request(transport: str = 'rest', request_type=environments.LoadSnapshotRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.load_snapshot(request) - - -def test_load_snapshot_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.DatabaseFailoverRequest, - dict, -]) -def test_database_failover_rest(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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.database_failover(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - -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 - - -@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, "pre_database_failover") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = environments.DatabaseFailoverRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.database_failover(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_database_failover_rest_bad_request(transport: str = 'rest', request_type=environments.DatabaseFailoverRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.database_failover(request) - - -def test_database_failover_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - environments.FetchDatabasePropertiesRequest, - dict, -]) -def test_fetch_database_properties_rest(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 = 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 - 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 - -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 - - 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", ))) - - -@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, "pre_fetch_database_properties") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = environments.FetchDatabasePropertiesResponse.to_json(environments.FetchDatabasePropertiesResponse()) - - request = environments.FetchDatabasePropertiesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = environments.FetchDatabasePropertiesResponse() - - client.fetch_database_properties(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_fetch_database_properties_rest_bad_request(transport: str = 'rest', request_type=environments.FetchDatabasePropertiesRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.fetch_database_properties(request) - - -def test_fetch_database_properties_rest_error(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = EnvironmentsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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) - - -def test_environments_rest_lro_client(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_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) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = EnvironmentsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = 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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = 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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = 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 c69b17a0f398..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py +++ /dev/null @@ -1,2739 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import 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.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 - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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("client_class,transport_class,transport_name", [ - (ImageVersionsClient, transports.ImageVersionsGrpcTransport, "grpc"), - (ImageVersionsClient, transports.ImageVersionsRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_image_versions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_image_versions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == image_versions.ListImageVersionsRequest() - - -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_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ImageVersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_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() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == image_versions.ListImageVersionsRequest() - -@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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_image_versions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[client._client._transport.list_image_versions] = mock_object - - request = {} - await client.list_image_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.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_object.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=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_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 = () - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_image_versions(request={}) - - assert pager._metadata == expected_metadata - - 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=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__', 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=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__', 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 - - -@pytest.mark.parametrize("request_type", [ - image_versions.ListImageVersionsRequest, - dict, -]) -def test_list_image_versions_rest(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 = 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 - 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' - -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 - - -@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, "pre_list_image_versions") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = image_versions.ListImageVersionsResponse.to_json(image_versions.ListImageVersionsResponse()) - - request = image_versions.ListImageVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = image_versions.ListImageVersionsResponse() - - client.list_image_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_image_versions_rest_bad_request(transport: str = 'rest', request_type=image_versions.ListImageVersionsRequest): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_image_versions(request) - - -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 - - 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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ImageVersionsClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = 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) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ImageVersionsAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = 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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = 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=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ImageVersionsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = 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/google/cloud/orchestration/airflow/service/gapic_version.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service/gapic_version.py index 0688549d000d..558c8aab67c5 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service/gapic_version.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_version.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_version.py index 0688549d000d..558c8aab67c5 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_version.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/__init__.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/__init__.py index 1e53dbea48d4..85ed7ebc134a 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/__init__.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/__init__.py @@ -23,6 +23,7 @@ from .services.environments import EnvironmentsAsyncClient, EnvironmentsClient from .services.image_versions import ImageVersionsAsyncClient, ImageVersionsClient from .types.environments import ( + AirflowMetadataRetentionPolicyConfig, CheckUpgradeRequest, CheckUpgradeResponse, CloudDataLineageIntegration, @@ -94,6 +95,7 @@ __all__ = ( "EnvironmentsAsyncClient", "ImageVersionsAsyncClient", + "AirflowMetadataRetentionPolicyConfig", "CheckUpgradeRequest", "CheckUpgradeResponse", "CloudDataLineageIntegration", diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py index 0688549d000d..558c8aab67c5 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py index 018e10860877..0a12b6cd1c3f 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py @@ -14,6 +14,7 @@ # limitations under the License. # from .environments import ( + AirflowMetadataRetentionPolicyConfig, CheckUpgradeRequest, CheckUpgradeResponse, CloudDataLineageIntegration, @@ -83,6 +84,7 @@ from .operations import OperationMetadata __all__ = ( + "AirflowMetadataRetentionPolicyConfig", "CheckUpgradeRequest", "CheckUpgradeResponse", "CloudDataLineageIntegration", diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py index 33c7b7195135..b83e81eb209b 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py @@ -76,6 +76,7 @@ "WorkloadsConfig", "DataRetentionConfig", "TaskLogsRetentionConfig", + "AirflowMetadataRetentionPolicyConfig", "StorageConfig", "RecoveryConfig", "ScheduledSnapshotsConfig", @@ -1443,9 +1444,11 @@ class EnvironmentConfig(proto.Message): multiple chunks, each with a size of at least 4 hours. - If this value is omitted, Cloud Composer - components may be subject to maintenance at any - time. + 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 @@ -2608,6 +2611,9 @@ class TriggererResource(proto.Message): 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-*.*.\* and newer. + Attributes: cpu (float): Optional. CPU request and limit for a single @@ -2673,16 +2679,36 @@ class DataRetentionConfig(proto.Message): 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): @@ -2691,8 +2717,7 @@ class TaskLogsRetentionConfig(proto.Message): Attributes: storage_mode (google.cloud.orchestration.airflow.service_v1beta1.types.TaskLogsRetentionConfig.TaskLogsStorageMode): Optional. The mode of storage for Airflow - workers task logs. For details, see - go/composer-store-task-logs-in-cloud-logging-only-design-doc + workers task logs. """ class TaskLogsStorageMode(proto.Enum): @@ -2719,6 +2744,45 @@ class TaskLogsStorageMode(proto.Enum): ) +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. diff --git a/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json b/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json index b85d03b7e36d..3fffc7af33c9 100644 --- a/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json +++ b/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-orchestration-airflow", - "version": "1.12.2" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json b/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json index 212a148e95a5..4c413d500bdb 100644 --- a/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json +++ b/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-orchestration-airflow-service", - "version": "1.12.2" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-orchestration-airflow/tests/unit/gapic/service_v1beta1/test_environments.py b/packages/google-cloud-orchestration-airflow/tests/unit/gapic/service_v1beta1/test_environments.py index 3065d1a2d3eb..caa5f98019f7 100644 --- a/packages/google-cloud-orchestration-airflow/tests/unit/gapic/service_v1beta1/test_environments.py +++ b/packages/google-cloud-orchestration-airflow/tests/unit/gapic/service_v1beta1/test_environments.py @@ -10931,7 +10931,12 @@ def test_create_environment_rest(request_type): } }, "data_retention_config": { - "task_logs_retention_config": {"storage_mode": 1} + "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, }, @@ -11856,7 +11861,12 @@ def test_update_environment_rest(request_type): } }, "data_retention_config": { - "task_logs_retention_config": {"storage_mode": 1} + "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, },